我需要确定对象数组中是否存在某个键。
这是一个示例数组:
arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
我试图这样做,但输出错误:
const objKeys = Object.keys(arrOfObj)
console.log('objKeys = ' + JSON.stringify(arrOfObj))
输出为索引号:
objKeys = ["0", "1", "2"]
我想要一个像这样的功能:
var isKeyPresent = checkKeyPresenceInArray('mainKey3')
请注意,尽管我只需要检查对象中的最高级别-在上面的示例中,这些是主键(mainKey1
等),并且它们的内容是动态的(其他一些对象具有深层嵌套的对象)里面,有些则不然。
帮助!
答案 0 :(得分:5)
您可以尝试使用array.some()
:
let checkKeyPresenceInArray = key => arrOfObj.some(obj => Object.keys(obj).includes(key));
let arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
let checkKeyPresenceInArray = key => arrOfObj.some(obj => Object.keys(obj).includes(key));
var isKeyPresent = checkKeyPresenceInArray('mainKey3')
console.log(isKeyPresent);
答案 1 :(得分:0)
您可以遍历数组,检查并查看是否有任何对象具有您要查找的密钥,如果有则返回true。如果找不到密钥,则for
循环将完成,并且将返回false。
arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
function arrayHasKey(arr, key) {
for (const obj of arr) {
if (key in obj) { return true; }
}
return false;
}
console.log(arrayHasKey(arrOfObj, "mainKey2"))
console.log(arrayHasKey(arrOfObj, "mainKey10"))
答案 2 :(得分:0)
这将起作用,它返回布尔值:
arrOfObj.hasOwnProperty('mainKey3');
答案 3 :(得分:0)
您可以将some
与hasOwnProperty
一起使用:
let checkKeyPresenceInArray = (key) => arrOfObj.some((o) => o.hasOwnProperty(key));
答案 4 :(得分:0)
您必须使用 hasOwnProperty
方法来检查键是否在该数组中的对象中可用-
var c = 0;
arrOfObj.forEach(e => {
if(e.hasOwnProperty("mainKey1")){
c++;
}
});
if(c > 0 && c == arrOfObj.length){
console.log("The key is found in all the objects in the array.");
}
else if(c == 0){
console.log("The key is not found in any objects in the array");
}
else{
console.log("The key is found in some objects in the array");
}