DEV Community

Anjan
Anjan

Posted on

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

In modern browsers you can use findIndex:

var students = [
 {id: 100 },
 {id: 200},
 {id: 300},
 {id: 400},
 {id: 500}
];
var 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

var students = [
 {id: 100 },
 {id: 200},
 {id: 300},
 {id: 400},
 {id: 500}
];
var index = -1;
var needle = 200;
var filteredRes = students.find(function(item, i){
 if(item.id === needle){
 index = i;
 return i;
 }
});
console.log(index, filteredRes);
/*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).

Top comments (0)