Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Find an object in an array of objects by property value in Javascript

In this chapter, you will learn about how to find an object in an array of objects by property value in Javascript. When you have an array of object and you just wanted to return an object which property value matches to a specific value.

Solution 1:
find(): For searching an object in the array of objects, we can use the find method, which returns the value of the first element in the provided array that satisfies the provided testing function. let’s write an example for the same

const persons = [
  { name: "John", email: 'john@john.com' },
  { name: "Stark", email: 'stark@stark.com' },
  { name: "Mickel", email: 'mickel@mickel.com' }
];

const searchResult = persons.find(item => item.name === "John");
console.log('Search result...');
console.log(searchResult);

// Output
// Search result...
// {name: "John", email: "john@john.com"}

Solution 2:
filter(): We can also use the filter method, which creates a new array with all elements that pass the test implemented by the provided function. let’s write an example for the same

const persons = [
  { name: "John", email: 'john@john.com' },
  { name: "Stark", email: 'stark@stark.com' },
  { name: "Mickel", email: 'mickel@mickel.com' }
];

const searchResult = persons.filter(function(item) {
  return item.name === 'John';
});

console.log('Search result...');
console.log(searchResult);

// Output
// Search result...
// {name: "John", email: "john@john.com"}

Solution 3:
for loop: We can also use the for loop, if value matched, then it returns the current object, let’s write an example for the same

const persons = [
  { name: "John", email: 'john@john.com' },
  { name: "Stark", email: 'stark@stark.com' },
  { name: "Mickel", email: 'mickel@mickel.com' }
];

for (var item in persons) {
  if (persons[item].name === 'John') {
    console.log(persons[item]);
  }
}

// Output
// {name: "John", email: "john@john.com"}