[英]How to check if a JSON Array object contains a Key
{
"myJSONArrayObject": [
{
"12": {}
},
{
"22": {}
}
]
}
我有上面的JSON Array对象。 如何检查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));
}
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 myIntegerKey
,12
和'12'
都将返回true
。
通过键检索对象的最直接方法是使用JavaScript括号表示法 。 同样,也可以使用find
方法遍历数组。
const obj = { myJSONArrayObject: [{ 12: {}, }, { 22: {}, }, ], }; const myIntegerKey = 12; const myObject = obj.myJSONArrayObject.find(item => item[myIntegerKey]); console.log("exists", myObject !== undefined);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.