{
"myJSONArrayObject": [
{
"12": {}
},
{
"22": {}
}
]
}
I have the above JSON Array object. How can I check if myJSONArrayObject
has a particular key?
This approach is not working :
let myIntegerKey = 12;
if (myJSONArrayObject.hasOwnProperty(myIntegerKey))
continue;
It seems to return false when it contains a key and true when it doesn't.
4 Answers 4
myJSONArrayObject
is an array. It doesn't have 12
as a property (Unless there are 12+ items in the array)
So, check if some
of the objects in the array have myIntegerKey
as a property
const exists = data.myJSONArrayObject.some(o => myIntegerKey in o)
or if myIntegerKey
is always an own property
const exists = data.myJSONArrayObject.some(o => o.hasOwnProperty(myIntegerKey))
Here's a snippet:
const data={myJSONArrayObject:[{"12":{}},{"22":{}}]},
myIntegerKey = 12,
exists = data.myJSONArrayObject.some(o => myIntegerKey in o);
console.log(exists)
1 Comment
"myJSONArrayObject"
is an array so you have to check hasOwnProperty
on each of it's elements:
let myIntegerKey = 12;
for (var obj in myJSONArrayObject) {
console.log(obj.hasOwnProperty(myIntegerKey));
}
Comments
The most direct method to retrieve the object by a key is to use JavaScript bracket notation. Use the find
method to iterate over the array, also.
const obj = {
myJSONArrayObject: [{
12: {},
},
{
22: {},
},
],
};
const myIntegerKey = 12;
const myObject = obj.myJSONArrayObject.find(item => item[myIntegerKey]);
console.log("exists", myObject !== undefined);
Comments
const obj = {
myJSONArrayObject: [
{
12: {},
},
{
22: {},
},
],
};
const myIntegerKey = '12';
const isExist = obj.myJSONArrayObject.findIndex((f) => { return f[myIntegerKey]; }) > -1;
console.log(isExist);
You can make it faster with every()
const obj = {
myJSONArrayObject: [
{
22: {},
},
{
12: {},
},
],
};
const myIntegerKey = '12';
const isExist = !obj.myJSONArrayObject
.every((f) => {
return !f[myIntegerKey];
});
console.log(isExist);
Note: Here the key name (
12: {},
) doesn't rely ontypeof myIntegerKey
,12
and'12'
both will returntrue
.
[{ "id": 12, "value": {} }, { "id": 22, "value": {} }]
. Way easier to search/transform than when every object inside the array has different keys.