In JavaScript, we can use the Array.prototype.find()
method to find an object by ID in an array of objects.
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
.
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)
Array.prototype.find()
method to find an object with id=3
.