EN
JavaScript - find object by id in array of objects
3
points
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