Q:

How to Find an Object by Property Value in an Array of JavaScript Objects

0

How to Find an Object by Property Value in an Array of JavaScript Objects

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the find() Method

You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

The following example shows how to find an object by id in an array of JavaScript objects.

// Sample array
var myArray = [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Peter"},
    {"id": 3, "name": "Harry"}
];

// Get the Array item which matchs the id "2"
var result = myArray.find(item => item.id === 2);

console.log(result.name);  // Prints: Peter

Alternatively, if you want to find the index of the matched item in the array, you can use the findIndex() method as shown in the following example:

// Sample array
var myArray = [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Peter"},
    {"id": 3, "name": "Harry"}
];

// Get the index of Array item which matchs the id "2"
var index = myArray.findIndex(item => item.id === 2);

console.log(index);  // Prints: 1
console.log(myArray[index].name);  // Prints: Peter

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get Month Name from a Date in JavaScript... >>
<< How to Parse a String to a Date Object in JavaScri...