Languages
[Edit]
EN

JavaScript - find object in array

3 points
Created by:
elmer
646

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));

 

References

Alternative titles

  1. JavaScript - find object by property in array of objects
  2. JavaScript - get array element by object property
  3. JavaScript - get item from array of objects by property value
  4. JavaScript - find value in array of objects
  5. JavaScript - Find object in array by one of its properties
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join