0

If I have only one object like below..

   var json = { "key1" : "100", "key2" : "200", "key3" : "300" }

I already know that we can find the index of "key2" like this..

var json = { "key1" : "100", "key2" : "200", "key3" : "300" }
var keytoFind = "key2";
var index = Object.keys(json).indexOf(keytoFind);
alert(index); // 1

But, now I have an array of objects in JSON like below.

var jsonArray = [{
    "key1": 1000,
    "key2": 1330
}, {
    "key3": 900,
    "key4": 600
}, {
    "key5": 390,
    "key6": 290
}]

I want to get the index of an object of key say "key3" in this JSON array - which is 1.

Mr. Black
  • 11,692
  • 13
  • 60
  • 85
user2644620
  • 199
  • 1
  • 10
  • 37
  • Does this answer your question? [How to find index of an object by key and value in an javascript array](https://stackoverflow.com/questions/11258077/how-to-find-index-of-an-object-by-key-and-value-in-an-javascript-array) – Heretic Monkey Nov 03 '20 at 19:15

2 Answers2

2

You can use ES2015 array method:

jsonArray.findIndex(item => Object.keys(item).includes("key3"));
0

You can also use ("key3" in obj) condition:

var jsonArray = [{
  "key1": 1000,
  "key2": 1330
}, {
  "key3": 900,
  "key4": 600
}, {
  "key5": 390,
  "key6": 290
}]

jsonArray.forEach((obj, i) => {
  ('key3' in obj) ? console.log(i): null;
});
MWO
  • 2,627
  • 2
  • 10
  • 25