thugsb thugsb - 2 years ago 176
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download