Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检查具有多个对象(javascript)的数组中是否存在值?_Javascript_Arrays_If Statement_Key - Fatal编程技术网

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

如何检查具有多个对象(javascript)的数组中是否存在值?,javascript,arrays,if-statement,key,Javascript,Arrays,If Statement,Key,因此,我的数组如下所示: let array = [ {"object1":1}, {"object2":2}, {"object3":3} ]; if ("opensprint1" in array){ console.log("yes, this is in the array"); } else { console.log("no, this is not in the array"); }; 例如,我想做的是检查“object1”是否存在。我更喜欢纯J

因此,我的数组如下所示:

let array = [
    {"object1":1},
    {"object2":2},
    {"object3":3}
];
if ("opensprint1" in array){
  console.log("yes, this is in the array");
} else {
  console.log("no, this is not in the array");
};
例如,我想做的是检查“object1”是否存在。我更喜欢纯Javascript

我这样做是为了处理大量数据,因此我的代码需要如下所示:

let array = [
    {"object1":1},
    {"object2":2},
    {"object3":3}
];
if ("opensprint1" in array){
  console.log("yes, this is in the array");
} else {
  console.log("no, this is not in the array");
};
注意:我曾尝试在JS中使用(in)函数和(hasOwnProperty),但两者都不起作用


有什么想法吗?

您正在尝试筛选一组对象。您可以将自定义函数传递到,定义自定义搜索函数。看起来您希望基于密钥的存在进行搜索。如果返回任何内容,则该键存在于对象数组中

let数组=[{
“对象1”:1
},
{
“对象2”:2
},
{
“对象3”:3
}
];
const filterByKey=(arr,keyName)=>
array.filter(obj=>Object.keys(obj).includes(keyName)).length>0;
log(filterByKey(数组'object1');
log(filterByKey(数组'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");
}
let数组=[
{“object1”:1},
{“object2”:2},
{“object3”:3}
];
让targetkey=“opensprint1”;
设exists=-1;
for(设i=0;i=0){
打破
}
}
如果(存在>=0){
log(“是的,这在数组中”);
}否则{
log(“不,这不在数组中”);
}
检查数组键,以便使用:

if ("0" in array){
但实际上,您需要检查一些数组元素是否获得了该键:

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

在这种情况下,我认为最有效的方法之一是对
和进行
中断
操作,如:

let数组=[
{“object1”:1},
{“object2”:2},
{“object3”:3}
];
存在=错误;

因为(让i=0;i.some是目前为止最好的方法,我认为后面的实现就像我在回答中所说的那样,
if(array[i].object1){
在这里有点危险,因为
{object1:0}
将无法与之相匹配。非常感谢您的帮助。谢谢@hodrobond