user2644620
user2644620

Reputation: 199

javascript json How to get index of key in json array

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.

Upvotes: 0

Views: 989

Answers (2)

MWO
MWO

Reputation: 2806

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

Upvotes: 0

You can use ES2015 array method:

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

Upvotes: 2

Related Questions