To find an object by its id
property in an array of JavaScript objects, you can use the find()
method, which returns the first element in the array that satisfies the provided testing function. Here’s an example:
let myArray = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
let obj = myArray.find(item => item.id === 2);
console.log(obj); // { id: 2, name: 'Jane' }
Alternatively, you can use the filter()
method, which returns an array of elements that satisfy the provided testing function. In this case, you can simply access the first element of the returned array. Here’s an example:
let myArray = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
let obj = myArray.filter(item => item.id === 2)[0];
console.log(obj); // { id: 2, name: 'Jane' }
If you are working with a very large array and need to optimize for performance, you may want to consider using a different data structure, such as an object or a map, which can allow you to access elements by key in constant time.