WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

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

Topic: JavaScript / jQueryPrev|Next

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

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties