Find Object In Array With Certain Property Value In JavaScript

July 7, 2020 by Andreas Wik

javascript find function

If you have an array of objects and want to extract a single object with a certain property value, e.g. id should be 12811, then find() has got you covered.

My array:

const students = [{
	id: 14400,
    name: 'K. Kelly', 
    year: 2
}, {
	id: 12811,
    name: 'A. Potter', 
    year: 3
}, {
	id: 22198,
    name: 'J. Simpson', 
    year: 1
}]

 

I want to find the object with an id of 12811. find() takes in a testing function. We want the object’s id property to match our variable id‘s value.

const id = 12811

const student = students.find(element => element.id === id)

console.log(student.name)
// "A. Potter"

 

JSFiddle:

 

Note: find() stops iterating over the array when it finds the first match and returns it. If you want to fetch multiple array items, then check outĀ filter instead.

Hope it helps.

 

Share this article

Recommended articles