Find object in array by property in JavaScript

Find first object

ECMAScript 2015

The find() method returns the value of the first item in the array based on the result of the provided testing function. In 2020 this function has 94,8% browser support, which should pretty safe to use without pollyfills.

// grab the Array item which matchs the id "1"
var item = myArray.find(item => item.id === 1);

// print
console.log(item.name);

Index of object

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

// grab the Array item which matchs the id "1"
myArray.findIndex(x => x.id === '1');

Array of matching elements

If you want to get an array of matching elements, use the filter() method instead. This will return an array of objects.

myArray.filter(x => x.id === '45');

…and last jQuery :-)


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

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
}