Languages
[Edit]
EN

JavaScript - find object by id in array of objects

3 points
Created by:
Blessing-D
574

In this article, we would like to show you how to find object by id in array of objects using JavaScript.

Warning: the below solutions appeared in ES6 (around 2016), so it is good to use Polyfil if needed.

 

1. Find value

In this example, we use find() method to find object in array of objects with id = 2 and get its name property value.

// ONLINE-RUNNER:browser;

const array = [
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 3, name: 'C' }
];

const result = array.find(object => object.id === 2).name;

console.log(result); // B

2. Find index

In this example, we use findIndex() method to find object in array of objects with id = 2 and get its index.

// ONLINE-RUNNER:browser;

const array = [
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 3, name: 'C' }
];

const result = array.findIndex(object => object.id === 2);

console.log(result); // 1

 

See also

  1. JavaScript - find object in array

  2. JavaScript - get index of item in array

References

  1. Array.prototype.find() - JavaScript | MDN
  2. Array.prototype.findIndex() - JavaScript | MDN

Alternative titles

  1. JavaScript - find index of object whose attributes match a search
  2. JavaScript - find index of object in array by key and value
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