所以我的数组看起来像这样:
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 )函数,但都没有成功。
有什么想法吗?
发布于 2018-07-25 03:15:57
if ("opensprint1" in array){
它检查数组键,因此它将与以下命令一起工作:
if ("0" in array){
但实际上,您需要检查一些数组元素是否获得了该键:
if(array.some( el => "opensprint1" in el))
发布于 2018-07-25 02:58:09
您正在尝试过滤对象数组。您可以将一个自定义函数传递给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'));
发布于 2018-07-25 03:02:11
这可能会对你有帮助
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");
}
https://stackoverflow.com/questions/51505647
复制相似问题