Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator
object
array

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

Shubham Singh Kshatriya

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)
Finding an object by ID in an array of JavaScript objects

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.

RELATED TAGS

javascript
communitycreator
object
array

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring