Question

Find an Object in a JavaScript Array by Property Value

javascriptarraysjavascript-objects

Question

Given an array of objects such as:

const myArray = [
  { id: "73", foo: "bar" },
  { id: "45", foo: "bar" }
];

The array structure cannot be changed. If an ID value of 45 is provided, how can you find the object whose id is "45" and retrieve its foo value ("bar") using JavaScript or jQuery?

Short Answer

You will learn how to search an array of objects for a matching property value. In particular, you will use Array.prototype.find() to get one matching object, safely read its property, and handle the important difference between numeric and string IDs.

Concept

An array can contain objects, and each object can hold named properties such as id and foo.

const item = { id: "45", foo: "bar" };

To locate an object by one of its properties, test every object until its property matches the value you need. Modern JavaScript provides find() for this exact job:

const match = myArray.find(item => item.id === "45");

find() returns the first matching object. If no object matches, it returns undefined.

This matters because arrays from APIs, JSON files, form data, and databases commonly contain records represented as objects. Searching them by an identifier is a routine task in application code.

A key detail in the original array is that IDs are strings:

{ id: "45", foo: "bar" }

So the strict comparison value should also be a string ("45"), not the number 45.

Mental Model

Think of the array as a row of labelled folders. Each folder is an object, and every folder has an id label.

find() walks from left to right, checks each label, and stops as soon as it finds the folder with the requested label. It then hands you that whole folder.

[ folder id=73 ] -> not a match
[ folder id=45 ] -> match; stop and return it

After you have the folder, access foo like you would read a field written inside it: match.foo.

Take Quiz

Syntax and Examples

Use find() when you expect zero or one item and want the first matching object.

const myArray = [
  { id: "73", foo: "bar" },
  { id: "45", foo: "bar" },
  { id: "19", foo: "baz" }
];

const requestedId = "45";
const item = myArray.find(entry => entry.id === requestedId);

console.log(item);
// { id: "45", foo: "bar" }

console.log(item?.foo);
// "bar"

The callback entry => entry.id === requestedId is run for each object:

  • entry is the current object.
  • It returns true when the ID matches.
  • find() returns that object immediately.

Use optional chaining (item?.foo) when a match may not exist. It evaluates to undefined instead of throwing an error.

If the incoming ID is a number but the stored IDs are strings, normalize one side deliberately:

const requestedId = 45;
const item = myArray.find(entry => entry.id === String(requestedId));

console.log(item?.foo); // "bar"

jQuery option

jQuery has $.grep(), but native find() is clearer for modern JavaScript:

const matches = $.grep(myArray, function (entry) {
  return entry.id === "45";
});

const item = matches[0];
console.log(item?.foo); // "bar"

$.grep() produces an array of all matches, so [0] selects the first one.

Step by Step Execution

Consider this code:

const records = [
  { id: "73", foo: "first" },
  { id: "45", foo: "bar" },
  { id: "88", foo: "last" }
];

const requestedId = "45";
const record = records.find(item => item.id === requestedId);
const value = record?.foo;

console.log(value);

Execution trace:

  1. records is created with three objects.
  2. requestedId is set to the string "45".
  3. find() checks the first object: "73" === "45" is false.
  4. It checks the second object: "45" === "45" is true.
  5. find() stops; it does not need to inspect the third object.
  6. record now refers to { id: "45", foo: "bar" }.
  7. record?.foo reads "bar".
  8. The console prints bar.

Real World Use Cases

Searching object arrays by a property is useful in many places:

  • Shopping cart: find a cart line by productId before changing its quantity.
  • User interfaces: find a selected country, category, or menu option by its ID.
  • API data: find a user or order in a response array.
  • Configuration: find a feature flag or environment setting by name.
  • Data import: find a record with a matching external reference before updating it.

Example: finding a user selected from a dropdown:

const users = [
  { id: "u1", name: "Ava" },
  { id: "u2", name: "Noah" }
];

const selectedUserId = "u2";
const selectedUser = users.find(user => user.id === selectedUserId);

console.log(selectedUser?.name); // "Noah"
Take Quiz

Real Codebase Usage

In production code, developers usually separate lookup, validation, and use of the result.

Validate a required record with a guard clause

function getProductName(products, productId) {
  const product = products.find(item => item.id === String(productId));

  if (!product) {
    return "Unknown product";
  }

  return product.name;
}

The early return handles the missing case before the rest of the function continues.

Build a lookup map for repeated searches

For a small array or one lookup, find() is simple and appropriate. If code repeatedly searches a large, mostly fixed array, create a Map once:

const products = [
  { id: "73", name: "Keyboard" },
  { id: "45", name: "Mouse" }
];

const productsById = new Map(products.map(product => [product.id, product]));

const product = productsById.get("45");
console.log(product?.name); // "Mouse"

This makes later lookups direct and clearly expresses that IDs are keys.

Common Mistakes

Comparing a number to a string with ===

The original objects store IDs as strings. This does not match:

const item = myArray.find(entry => entry.id === 45); // undefined

Use matching types instead:

const item = myArray.find(entry => entry.id === "45");

Or convert an external number intentionally with String(requestedId).

Reading a property before checking for no match

This can throw because find() can return undefined:

const item = myArray.find(entry => entry.id === "999");
console.log(item.foo); // TypeError

Use optional chaining or a guard:

console.log(item?.foo);

Using filter() when only one item is needed

const item = myArray.filter(entry => entry.id === "45");
console.log(item.foo); // undefined: item is an array

filter() always returns an array. Prefer find() for the first object.

Using loose equality to hide inconsistent data

entry.id == 45

Loose equality may make string and number IDs appear to work, but implicit conversion can conceal data problems. Prefer === and normalize the type explicitly.

Assuming IDs are unique without confirming it

find() returns only the first match. If duplicates are valid and all matches matter, use filter().

Comparisons

ToolResultBest use
find()First matching object, or undefinedLooking up one record by ID
filter()Array of every matching objectCollecting all matching records
findIndex()Index of first match, or -1You need an array position for update/removal
some()true or falseChecking whether a match exists
Map#get()Value for a key, or undefinedMany repeated lookups by a unique key

Examples:

const items = [
  { id: "45", foo: "bar" },
  { id: "45", foo: "another" }
];

items.find(item => item.id === "45");
// { id: "45", foo: "bar" }

items.filter(item => item.id === "45");
// [{ id: "45", foo: "bar" }, { id: "45", foo: "another" }]

items.findIndex(item => item.id === "45");
// 0

items.some(item => item.id === "45");
// true
Take Quiz

Cheat Sheet

// First object whose property matches
const item = array.find(entry => entry.id === "45");

// Read safely when item may be missing
const value = item?.foo;

// Convert an incoming numeric ID when stored IDs are strings
const item = array.find(entry => entry.id === String(incomingId));

// All matching objects
const matches = array.filter(entry => entry.id === "45");

// Position of first match
const index = array.findIndex(entry => entry.id === "45");

// Does at least one match exist?
const exists = array.some(entry => entry.id === "45");
  • find() returns an object or undefined.
  • filter() always returns an array.
  • Prefer === over ==.
  • Ensure both compared IDs have the same type.
  • Use ?. or a guard clause if a match is optional.

FAQ

How do I find an object in a JavaScript array by ID?

Use find():

const item = array.find(entry => entry.id === "45");

Why does find() return undefined even though the ID looks correct?

Check the types. For example, "45" === 45 is false. If array IDs are strings, compare them with a string or convert the incoming value using String(id).

How do I get a property from the matching object?

Find the object first, then read its property safely:

const foo = array.find(entry => entry.id === "45")?.foo;

Should I use find() or filter() to search by ID?

Use find() for one expected result. Use filter() if you need every matching object.

Does find() modify the original array?

No. It only returns a reference to an existing object or undefined; it does not add, remove, or reorder array entries.

Can I use jQuery to search an object array?

Yes, $.grep() can filter it, but native Array.prototype.find() is usually the more direct modern JavaScript choice.

What happens if there are duplicate IDs?

find() returns the first matching object. Use filter() to retrieve all objects with that ID.

Take Quiz

Mini Project

Description

Create a small product lookup function for a catalog. A caller provides a product ID, and the function returns a useful product description or a fallback message when the product does not exist. This mirrors common API, cart, and admin-dashboard lookup code.

Goal

Find a product by ID in an array of objects and safely return its name and price.

Requirements

Use an array containing at least three product objects. Store product IDs as strings. Create a function that accepts a product ID. Return a formatted product description for a matching product. Return a clear fallback message when no product matches.

Take Quiz

Keep learning

Related questions

View more