Categories
JavaScript Answers

How to find an object in an array by one of its properties with JavaScript?

Spread the love

To find an object in an array by one of its properties with JavaScript, we call the find method.

For instance, we write

const newData = [
  { investor: "Sue", stocks: 0, options: 0, savings: 0 },
  { investor: "Rob", stocks: 0, options: 0, savings: 0 },
  { investor: "Liz", stocks: 0, options: 0, savings: 0 },
];
const investor = "Rob";
const res = newData.find((x) => x.investor === investor);

to call newData.find with a callback that checks whether the investor property in the object being looped through equals to investor.

The first instance of the object where the condition is returned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *