DEV Community

Anjan
Anjan

Posted on

2 1

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).

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay