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 .
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.
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:
entryis the current object.- It returns
truewhen the ID matches. find()returns that object immediately.
Use optional chaining (item?.foo) when a match may not exist. It evaluates to instead of throwing an error.
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:
recordsis created with three objects.requestedIdis set to the string"45".find()checks the first object:"73" === "45"isfalse.- It checks the second object:
"45" === "45"istrue.
Real World Use Cases
Searching object arrays by a property is useful in many places:
- Shopping cart: find a cart line by
productIdbefore 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"
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]));
product = productsById.();
.(product?.);
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
Comparisons
| Tool | Result | Best use |
|---|---|---|
find() | First matching object, or undefined | Looking up one record by ID |
filter() | Array of every matching object | Collecting all matching records |
findIndex() | Index of first match, or -1 | You need an array position for update/removal |
some() | true or false | Checking whether a match exists |
Map#get() | Value for a key, or undefined |
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 orundefined.
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 if you need every matching object.
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.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.