javascript tutorial - [Solved-5 Solutions] Finding object by id in an array of JavaScript objects - javascript - java script - javascript array



Problem:

Find object by id in an array of JavaScript objects

Solution 1:

an array:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
click below button to copy the code. By JavaScript tutorial team

Solution 2:

var result = $.grep(myArray, function(e){ return e.id == id; });
click below button to copy the code. By JavaScript tutorial team

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) {
  // not found
} else if (result.length == 1) {
  // access the foo property using result[0].foo
} else {
  // multiple items found
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

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

... now you can use lookup[id]...

click below button to copy the code. By JavaScript tutorial team

Solution 4:

myArray.find(x => x.id === '45').foo
click below button to copy the code. By JavaScript tutorial team

From MDN:

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

Solution 5:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return obj.id == '45' })
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Finding object by id in an array of JavaScript objects