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 queriedconst 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 consoleconsole.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 withid=3. - Line 21: We print the resultant object on the console.