EN
JavaScript - find object in array
3
points
In this article, we would like to show you how to find an object in array of objects in JavaScript.
There are three methods you can use to find object in array of objects:
find()
findIndex()
filter()
1. find()
method
The find()
method returns the first value in the array, if an element satisfies the provided testing function.
// ONLINE-RUNNER:browser;
const food = [
{name: 'Apple', type: 'fruit'},
{name: 'Broccoli', type: 'vegetable'},
{name: 'Banana', type: 'fruit'},
{name: 'Fries', type: 'fast-food'},
{name: 'Cherry', type: 'fruit'}
];
const result = food.find(item => item.name === 'Banana');
console.log(JSON.stringify(result, null, 4));
2. findIndex()
method
The findIndex()
method returns the index of the first element in the array that satisfies the provided testing function.
// ONLINE-RUNNER:browser;
const food = [
{name: 'Apple', type: 'fruit'},
{name: 'Broccoli', type: 'vegetable'},
{name: 'Banana', type: 'fruit'},
{name: 'Fries', type: 'fast-food'},
{name: 'Cherry', type: 'fruit'}
];
const result = food.findIndex(item => item.name === 'Broccoli');
console.log(JSON.stringify(result, null, 4));
3. filter()
method
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
Find a single object by name
property:
// ONLINE-RUNNER:browser;
const food = [
{name: 'Apple', type: 'fruit'},
{name: 'Broccoli', type: 'vegetable'},
{name: 'Banana', type: 'fruit'},
{name: 'Fries', type: 'fast-food'},
{name: 'Cherry', type: 'fruit'}
];
const result = food.filter(item => item.name === 'Broccoli');
console.log(JSON.stringify(result, null, 4));
Find multiple objects by type
property:
// ONLINE-RUNNER:browser;
const food = [
{name: 'Apple', type: 'fruit'},
{name: 'Broccoli', type: 'vegetable'},
{name: 'Banana', type: 'fruit'},
{name: 'Fries', type: 'fast-food'},
{name: 'Cherry', type: 'fruit'}
];
const result = food.filter(item => item.type === 'fruit');
console.log(JSON.stringify(result, null, 4));