Program-Me-Rev
Program-Me-Rev

Reputation: 6624

How to check if a JSON Array object contains a Key

{
  "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.

Upvotes: 0

Views: 7046

Answers (4)

Neel Rathod
Neel Rathod

Reputation: 2111

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 on typeof myIntegerKey, 12 and '12' both will return true.

Upvotes: 0

ctaleck
ctaleck

Reputation: 1665

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);

Upvotes: 0

adiga
adiga

Reputation: 35222

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)

Upvotes: 3

Olivenbaum
Olivenbaum

Reputation: 1006

"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));
}

Upvotes: 0

Related Questions