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?
Solution 1:
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. Otherwiseundefined
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).
Solution 2:
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
}
Solution 3:
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.
Solution 4:
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.
Solution 5:
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' })