How to find an object by ID in an array of JavaScript objects

Overview

In JavaScript, we can use the Array.prototype.find() method to find an object by ID in an array of objects.

Return value

This method returns the first object instance that matches the specified condition in the callback function. If none of the objects match the specified condition, this method returns undefined.

Example

Let's look at the code below:

// array of objects to be queried
const array = [
{
id: 1,
name: 'Shubham'
},
{
id: 2,
name: 'Parth'
},
{
id: 3,
name: 'Pratik'
}
]
// finding the object whose id is '3'
const object = array.find(obj => obj.id === 3);
// printing object on the console
console.log(object)

Explanation

  • Lines 2 to 15: We create an array of objects.
  • Line 18: We use the Array.prototype.find() method to find an object with id=3.
  • Line 21: We print the resultant object on the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources