Find object by id in an array of JavaScript objects

ID : 504

viewed : 122

Tags : javascriptarraysjavascript-objectsjavascript

Top 5 Answer for Find object by id in an array of JavaScript objects

vote vote

95

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

vote vote

90

As you are already using jQuery, you can use the grep function which is intended for searching an array:

var result = $.grep(myArray, function(e){ return e.id == id; }); 

The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo to get the value. Otherwise you should check the length of the resulting array. Example:

if (result.length === 0) {   // no result found } else if (result.length === 1) {   // property found, access the foo property using result[0].foo } else {   // multiple items found } 
vote vote

77

Another solution is to create a lookup object:

var lookup = {}; for (var i = 0, len = array.length; i < len; i++) {     lookup[array[i].id] = array[i]; }  ... now you can use lookup[id]... 

This is especially interesting if you need to do many lookups.

This won't need much more memory since the IDs and objects will be shared.

vote vote

69

ECMAScript 2015 (JavaScript ES6) provides the find() method on arrays:

var myArray = [  {id:1, name:"bob"},  {id:2, name:"dan"},  {id:3, name:"barb"}, ]  // grab the Array item which matchs the id "2" var item = myArray.find(item => item.id === 2);  // print console.log(item.name);

It works without external libraries. But if you want older browser support you might want to include this polyfill.

vote vote

59

Underscore.js has a nice method for that:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.] obj = _.find(myArray, function(obj) { return obj.id == '45' }) 

Top 3 video Explaining Find object by id in an array of JavaScript objects

Related QUESTION?