How to find an object from an array of objects using the property value in JavaScript?

Published January 29, 2021

To find an object from an array of objects, we can use the filter() method available in the array and then check to see the object property's value matches the value we are looking for in the filter() method.

To understand it clearly,

Consider an array of objects like this,

// array of objects
const objectsArr = [
  { name: "John Doe", age: 23 },
  { name: "Melina", age: 21 },
  { name: "Roy Dalton", age: 43 },
];

Our aim to find the object in the array which have the property age with the value of 21.

So let's use the filter() method in the objectsArr array. See the post on filter() method to understand how it works 😃.

// array of objects
const objectsArr = [
  { name: "John Doe", age: 23 },
  { name: "Melina", age: 21 },
  { name: "Roy Dalton", age: 43 },
];

// using filter() method
// to filter out the object we need
const objectWeNeed = objectsArr.filter((object) => {
  return object.age === 21;
});

console.log(objectWeNeed); // [ { age: 21, name: "Melina"} ]
  • If we return boolean true from the filter() method it will give out only that object in the array which matches the condition and discard the rest of the objects in the array.

To put it simply it will keep all the objects in the array which match the condition inside the filter() method.

And We have successfully found the object from an array of an object using the property's value.

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter