thugsb thugsb - 5 months ago 33x
Javascript Question

Find an object by property value in an array of JavaScript objects

I've got an array:

const myArray = [
{'id': '73','foo': 'bar'},
{'id': '45','foo': 'bar'}
/* and so on */

I'm being passed an
, and I want to get
for that object in the array.

How do I do this in JavaScript or using jQuery?


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 == 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) {
  // not found
} else if (result.length == 1) {
  // access the foo property using result[0].foo
} else {
  // multiple items found