Find object by key-value pair in an array of objects in JavaScript

This tutorial will show you how you can find objects by id in an array of objects in JavaScript. We will use the Array.prototype.find() method and for loop to find the object.

Using find() method

We can pass a condition as a parameter to the find() method and if the condition is satisfied it will return the value of the last element.

It will return undefined if the condition is not satisfied by the array element.

Here is the JavaScript program to find an object by id using find() method in an array of objects.

const array = [
  {id: 1, name: 'David'},
  {id: 2, name: 'Eric'},
  {id: 3, name: 'Mia'},
];


const foundObject = array.find(obj => obj.id === 2);

console.log(foundObject);

In the above program, I have created an array of objects called array that contains three objects.

Then I have used find() method to find the object whose id property is equal to 2. As the find() method iterates over each element in the array, it returns the first object that has an id property is equal to 2.

Output:

{ id: 2, name: 'Eric' }

 

for loop to find an object

Here is the JavaScript program to find an object by id using for loop in an array of objects.

const array = [
  {id: 1, name: 'David'},
  {id: 2, name: 'Eric'},
  {id: 3, name: 'Mia'},
];

function findObjectById(id, object) {
  for (let i = 0; i < array.length; i++) {
    if (object[i].id === id) {
      return object[i];
    }
  }
  return null;
}


const object = findObjectById(2, array);

console.log(object);

In the above program, the function findObjectById will iterate over the array of objects that is array and compare the id property of each object with the given id. If a match is found, the object will be returned. It will return null in case of completing the loop without finding a match.

Output:

{ id: 2, name: 'Eric' }

Leave a Reply

Your email address will not be published. Required fields are marked *