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.