JavaScript: finding a value in an array of objects

Steven Script
Aug 23, 2017 · 1 min read

Here’s a nice and clean way to find and retrieve an object, from an array of objects, that matches a given value:

let students = [
{ name: “John”, age: “18”, grade: “A” },
{ name: “Bob”, age: “20”, grade: “B” }
];
let bob= students.find(item => item.name === “Bob”);console.log(bob);// will output:
// { name: “Bob”, age: “20”, grade: “B” }

You can also use this approach to replace the found object:

let students = [
{ name: “John”, age: “18”, grade: “A” },
{ name: “Bob”, age: “20”, grade: “B” }
];
let bob = students.find((item, i) => {
if(item.name === “Bob”) {
students[i] = { name: "Bob Smith", age: "20", grade: "C" };
return true; // in order to quit the search
}
}
console.log(students);// will output:
// [ { name: “John”, age: “18”, grade: “A” }, { name: “Bob Smith”, age: “20”, grade: “C” } ]
)
Steven Script

Written by

I’m a Web Developer riding up and down the learning curve and sharing things as I go.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade