Anjan Dutta

How to get index from a JSON object with value: javascript

How to get index from a JSON object with value: javascript

How to get index from a JSON object with value?

In modern browsers you can use findIndex.

See the below example.

1var students = [
2 {id: 100 },
3 {id: 200},
4 {id: 300},
5 {id: 400},
6 {id: 500}
7];
8var index = students.findIndex(std=> std.id === 200);

But this function is not supported by even not so old versions of a few browser as well as in IE (EDGE supports it). So below is a workaround using javascript:

You can use either Array.forEach or Array.find or Array.filter

1var students = [
2 {id: 100 },
3 {id: 200},
4 {id: 300},
5 {id: 400},
6 {id: 500}
7];
8var index = -1;
9var needle = 200;
10var filteredRes = students.find(function(item, i){
11 if(item.id === needle){
12 index = i;
13 return i;
14 }
15});
16
17console.log(index, filteredRes);
18
19/*Result: 1 Object { id: 200 }*/

This method takes little more overhead as it loops through the whole object to search for the match. So, for lengthy JSON data, this method is not suggested(even though it gets the work done).