Categories
JavaScript Answers

How to find object by id in an array of JavaScript objects?

Spread the love

To find object by id in an array of JavaScript objects, we use the find method.

For instance, we write

const myArray = [
  { id: "73", foo: "bar" },
  { id: "45", foo: "bar" },
  //...
];
const foo = myArray.find((x) => x.id === "45").foo;

to call myArray.find with a callback that checks if the id property of the item is '45'.

If it’s true, then the object is returned.

And then we get the foo property of it.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.