如何检查 JSON 数组对象是否包含密钥


{
"myJSONArrayObject": [
{
"12": {}
},
{
"22": {}
}
]
}  

我有上面的 JSON 数组对象。如何检查myJSONArrayObject是否有特定的密钥?

此方法不起作用:

let myIntegerKey = 12;
if (myJSONArrayObject.hasOwnProperty(myIntegerKey))
continue;

当它包含键时,它似乎返回false,当它不包含键时,它似乎返回 true。

myJSONArrayObject

是一个数组。它没有12作为属性(除非数组中有 12+ 项)

因此,检查数组中是否有some对象具有myIntegerKey属性

const exists = data.myJSONArrayObject.some(o => myIntegerKey in o)

或者如果myIntegerKey始终是自己的财产

const exists = data.myJSONArrayObject.some(o => o.hasOwnProperty(myIntegerKey))

下面是一个片段:

const data={myJSONArrayObject:[{"12":{}},{"22":{}}]},
myIntegerKey = 12,
exists = data.myJSONArrayObject.some(o => myIntegerKey in o);
console.log(exists)

"myJSONArrayObject"

是一个数组,所以你必须检查它的每个元素hasOwnProperty

let myIntegerKey = 12;
for (var obj in myJSONArrayObject) {
console.log(obj.hasOwnProperty(myIntegerKey));
}

通过键检索对象的最直接方法是使用 JavaScript 括号表示法。还可以使用find方法循环访问数组。

const obj = {
myJSONArrayObject: [{
12: {},
},
{
22: {},
},
],
};
const myIntegerKey = 12;
const myObject = obj.myJSONArrayObject.find(item => item[myIntegerKey]);
console.log("exists", myObject !== undefined);

const obj = {
myJSONArrayObject: [
{
12: {},
},
{
22: {},
},
],
};
const myIntegerKey = '12';
const isExist = obj.myJSONArrayObject.findIndex((f) => { return f[myIntegerKey]; }) > -1;
console.log(isExist);

您可以使用every()使其更快

const obj = {
myJSONArrayObject: [
{
22: {},
},
{
12: {},
},
],
};
const myIntegerKey = '12';
const isExist = !obj.myJSONArrayObject
.every((f) => {
return !f[myIntegerKey];
});
console.log(isExist);

注意:这里的键名(12: {},)不依赖于typeof myIntegerKey12'12'两者都会返回true

最新更新