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.

1

2 Answers 2

2

You can use ES2015 array method:

jsonArray.findIndex(item => Object.keys(item).includes("key3"));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.