This post will discuss how to find a value in an array of objects in JavaScript.
1. Using Array.prototype.find() function
The recommended solution is to use the find() method that returns the first occurrence of an element in the array that satisfies the given predicate. The following code example demonstrates this by finding a person with the name John.
var obj = [
{ name: ‘Max’, age: 23 },
{ name: ‘John’, age: 20 },
{ name: ‘Caley’, age: 18 }
];
var found = obj.find(e => e.name === ‘John’);
console.log(found);
/*
Output: { name: ‘John’, age: 20 }
*/
2. Using Array.prototype.findIndex() function
Alternatively, you can use the findIndex() method, which is similar to the find() method but returns the index of the first occurrence of an element or -1 if no element is found.
var obj = [
{ name: ‘Max’, age: 23 },
{ name: ‘John’, age: 20 },
{ name: ‘Caley’, age: 18 }
];
var index = obj.findIndex(e => e.name === ‘John’);
if (index !== –1) {
console.log(obj[index]);
}
/*
Output: { name: ‘John’, age: 20 }
*/
3. Using Array.prototype.forEach() function
Here, the idea is to iterate over the given array using the forEach() method and determine whether the object is present in the array.
var obj = [
{ name: ‘Max’, age: 23 },
{ name: ‘John’, age: 20 },
{ name: ‘Caley’, age: 18 }
];
obj.forEach(o => {
if (o.name === ‘John’) {
console.log(o);
}
});
/*
Output: { name: ‘John’, age: 20 }
*/
4. Using Array.prototype.filter() function
Another plausible way is to filter the array to return all objects that pass the specified predicate. This can be easily done using the filter() method.
var obj = [
{ name: ‘Max’, age: 23 },
{ name: ‘John’, age: 20 },
{ name: ‘Caley’, age: 18 }
];
var found = obj.filter(e => e.name === ‘John’);
if (found.length > 0) {
console.log(found[0]);
}
/*
Output: { name: ‘John’, age: 20 }
*/
5. Using jQuery
The jQuery’s $.grep method works similarly to JavaScript’s native filter() method.
const { JSDOM } = require(“jsdom”);
const { window } = new JSDOM();
var $ = require(“jquery”)(window);
var obj = [
{ name: ‘Max’, age: 23 },
{ name: ‘John’, age: 20 },
{ name: ‘Caley’, age: 18 }
];
var found = $.grep(obj, e => e.name === ‘John’);
if (found.length > 0) {
console.log(found[0]);
}
/*
Output: { name: ‘John’, age: 20 }
*/
6. Using Lodash/Underscore Library
The Underscore and Lodash library have the _.filter method, similar to the JavaScript’s native filter() method. The following code example demonstrates the usage of the _.filter method.
var _ = require(‘lodash’);
var obj = [
{ name: ‘Max’, age: 23 },
{ name: ‘John’, age: 20 },
{ name: ‘Caley’, age: 18 }
];
var found = _.filter(obj, e => e.name === ‘John’);
if (found.length > 0) {
console.log(found[0]);
}
/*
Output: { name: ‘John’, age: 20 }
*/