0

I need to check key exist in object of object. I have array of object and in every object i have one other object. I need to check the key is existing in object of object

var myarr = [{
    hello: "world",
    payload: {
      kekek: 'sdfsdfsdf',
      baby: 'sdfsdfsdfds'
    }
  },
  {
    hello: "world",
    payload: {
      qwe: 'sdfsdfsdf',
      baby: 'sdfsdfsdfds'
    }
  }, {
    hello: "world",
    payload: {
      qwe: 'sdfsdfsdf',
      baby: 'sdfsdfsdfds'
    }
  },
  {
    hello: "world",
    payload: {
      asdf: 'sdfsdfsdf',
      baby: 'sdfsdfsdfds'
    }
  }
]



let pp = myarr.payload.hasOwnProperty('eekey')
console.log(pp).

I need to check kekek in payload.

Pritesh Mahajan
  • 4,974
  • 8
  • 39
  • 64
  • You have to loop over the list, and for each object in the list you should do something like: if(obj.payload.hasOwnProperty("eekey")) – Guy Cohen Jul 22 '21 at 14:42
  • The loop should be look like something like this: https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript – Guy Cohen Jul 22 '21 at 14:45
  • [Maybe this helps](https://stackblitz.com/edit/js-key-in-object?file=ObjectPathExplorer.js) – KooiInc Jul 23 '21 at 07:30

1 Answers1

3

If I understood correctly, you want to check if every of object of your array contains a specific key in payload property. If so, you can use in operator to check if a property is present in a object. You can improve this snippet by checking if value is defined.

let key = 'kekek';
const everyObjectHasKey = myarr.every(item => item.payload && key in item.payload);
console.log(everyObjectHasKey);

In this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every , you can see more about every method for arrays