JavaScript

Find one object by property in an array

Use Array.find when you want the first record matching a condition. It returns the record itself, or undefined if no element matches; it does not return an array of results.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const users = [{id: 1, name: "Morgan"}, {id: 2, name: "River"}];
const user = users.find(item => item.id === 2);
console.log(user?.name ?? "Not found");

How it works

The callback runs in index order until it succeeds. Strict equality avoids treating the number 2 and the string "2" as interchangeable. Optional chaining and a nullish fallback make the no-match case explicit without throwing on user.name.

Limits and mistakes

Find returns a reference to the stored object. Editing the result edits that same record in the array. If IDs are not unique, the first match wins; frequent lookups may be clearer with a Map.

Check the result

The example prints River. Change the requested ID to 99 and confirm the fallback appears. Test duplicate IDs if uniqueness is not guaranteed.

Sources

Reference documentation for the behavior used in this guide: