繁体   English   中英

如何检查具有多个对象的数组中的值是否存在-JavaScript?

[英]How can I check if a value exists in an array with multiple objects - javascript?

所以我的数组看起来像这样:

let array = [
    {"object1":1},
    {"object2":2},
    {"object3":3}
];

我想要做的是例如检查“ object1”是否存在。 我更喜欢纯Javascript。

我正在对大量数据进行此操作,因此我的代码需要是这样的:

if ("opensprint1" in array){
  console.log("yes, this is in the array");
} else {
  console.log("no, this is not in the array");
};

注意:我试图在JS和(hasOwnProperty)中使用(in)函数,但都没有用。

有任何想法吗?

if ("opensprint1" in array){

该检查数组键,因此它可以与:

if ("0" in array){

但是实际上您想检查某些数组元素是否具有该键:

if(array.some( el => "opensprint1" in el))

您正在尝试过滤对象数组。 您可以将自定义函数传递给Array.prototype.filter ,从而定义一个自定义搜索函数。 看起来您想根据键的存在进行搜索。 如果返回任何内容,则该键存在于对象数组中。

 let array = [{ "object1": 1 }, { "object2": 2 }, { "object3": 3 } ]; const filterByKey = (arr, keyName) => array.filter(obj => Object.keys(obj).includes(keyName)).length > 0; console.log(filterByKey(array, 'object1')); console.log(filterByKey(array, 'object5')); 

大致相当于:

 let array = [{ "object1": 1 }, { "object2": 2 }, { "object3": 3 } ]; const filterByKey = (arr, keyName) => { // iterate each item in the array for (let i = 0; i < arr.length; i++) { const objectKeys = Object.keys(arr[i]); // take the keys of the object for (let j = 0; j < objectKeys.length; j++) { // see if any key matches our expected if(objectKeys[i] === keyName) return true } } // none did return false; } console.log(filterByKey(array, 'object1')); console.log(filterByKey(array, 'object5')); 

这可能对您有帮助

let array = [
    {"object1":1},
    {"object2":2},
    {"object3":3}
];

let targetkey = "opensprint1";
let exists  = -1;
for(let i = 0; i < array.length; i++) {
    let objKeys = Object.keys(array[i]);
    exists = objKeys.indexOf(targetkey);
    if (exists >= 0) {
        break;
    }
}

if (exists >= 0) {
    console.log("yes, this is in the array");
} else {
   console.log("no, this is not in the array");
}

在这种情况下,我认为最有效的方法之一是进行for and break

 let array = [ {"object1":1}, {"object2":2}, {"object3":3} ]; exist = false; for(let i = 0; i<array.length; i++){ if("object1" in array[i]){ exist = true;//<-- We just know the answer we want break;//<-- then stop the loop } } console.log(exist); 

当迭代找到正确的情况时,停止迭代。 我们无法在.map.filter等中执行break 。因此,迭代次数越少。 我认为.some()也是这样

let array = [
 { "object1": 1 },
 { "object2": 2 },
 { "object3": 3 }
];

let checkKey = (key) => {
 var found = false;
 array.forEach((obj) => {
     if (!(obj[key] === undefined)) {
         found = true;
         array.length = 0;
     }
 });
 return found;
}
console.log(checkKey("object2"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM