Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object by id in an array of JavaScript objects

I've got an array:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.] 

I'm unable to change the structure of the array. I'm being passed an id of 45, and I want to get 'bar' for that object in the array.

How do I do this in JavaScript or using jQuery?

like image 703
thugsb Avatar asked Sep 09 '11 15:09

thugsb


People also ask

How do you find the object of an array of objects?

Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

How do I find the ID of an array of objects?

Overview. In JavaScript, we can use the Array. prototype. find() method to find an object by ID in an array of objects.


1 Answers

Use the find() method:

myArray.find(x => x.id === '45').foo; 

From MDN:

The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


If you want to find its index instead, use findIndex():

myArray.findIndex(x => x.id === '45'); 

From MDN:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.


If you want to get an array of matching elements, use the filter() method instead:

myArray.filter(x => x.id === '45'); 

This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

myArray.filter(x => x.id === '45').map(x => x.foo); 

Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).

like image 62
Michał Perłakowski Avatar answered Sep 19 '22 18:09

Michał Perłakowski