To update an object’s property inside an array of objects in JavaScript without mutating the original array or its existing objects, use Array.prototype.map() paired with object spread ({ ...item, [prop]: nextValue }) to return a new array where only the matching object(s) receive a new shallow copy with the updated property. This non-mutating pattern keeps state predictable in React, Redux, and Node.js data pipelines while safely guarding against invalid inputs or missing keys.
1. Updating a Matching Object Non-Mutatingly with .map() and Spread
Match items by a unique identifier (such as id) inside .map(), returning a shallow-copied object with the updated property for matches and returning untouched items as-is:
// Non-mutating helper to update a property on objects matching a predicate
function updateObjectPropertyInArray(items, predicate, key, value) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an array.");
}
if (typeof predicate !== "function") {
throw new TypeError("Expected predicate to be a function.");
}
if (typeof key !== "string" || key.length === 0) {
throw new TypeError("Expected key to be a non-empty string.");
}
return items.map((item) => {
if (item !== null && typeof item === "object" && predicate(item)) {
return {
...item,
[key]: value
};
}
return item;
});
}
// Example usage:
const users = [
{ id: 1, name: "Amina", active: false },
{ id: 2, name: "Bilal", active: true }
];
const updatedUsers = updateObjectPropertyInArray(
users,
(user) => user.id === 1,
"active",
true
);
console.log(updatedUsers);
// [{ id: 1, name: "Amina", active: true }, { id: 2, name: "Bilal", active: true }]
console.log(users[0].active); // false (original object and array remain unmutated)
- Structural sharing: Unchanged items keep their original object references, while only matched items get a new shallow object copy.
- Computed property key
[key]: value: Lets you pass dynamic property names cleanly while guarding against empty or non-string keys.
2. Updating Only the First Match vs. All Matches
By default, .map() updates every element where predicate(item) returns true; if you only want to update the first matching object (for instance, when IDs might not be guaranteed unique), track whether a match has already been applied:
// Update only the first matching object in a non-mutating way
function updateFirstMatchInArray(items, predicate, patch) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an array.");
}
if (typeof predicate !== "function") {
throw new TypeError("Expected predicate to be a function.");
}
if (patch === null || typeof patch !== "object" || Array.isArray(patch)) {
throw new TypeError("Expected patch to be a plain object.");
}
let didUpdate = false;
return items.map((item) => {
if (!didUpdate && item !== null && typeof item === "object" && predicate(item)) {
didUpdate = true;
return {
...item,
...patch
};
}
return item;
});
}
// Example usage:
const queue = [
{ jobId: "j1", status: "pending", retries: 0 },
{ jobId: "j1", status: "pending", retries: 0 }
];
const nextQueue = updateFirstMatchInArray(
queue,
(job) => job.jobId === "j1",
{ status: "running", retries: 1 }
);
console.log(nextQueue);
// Only the first item becomes { jobId: "j1", status: "running", retries: 1 }
- Patch multiple fields at once: Spreading
...patch({ ...item, ...patch }) updates several properties cleanly in one pass. - Stop after first hit: The
didUpdateflag avoids modifying duplicate records later in the array.
3. Shallow vs. Nested Object Properties and In-Place Mutation Caveats
Object spread ({ ...item, count: 5 }) only copies top-level enumerable properties; if you update a nested object property (such as meta.theme), spread that nested object as well so you do not accidentally mutate shared nested references:
// Non-mutating update for a nested property inside an array item
function setNestedPropertyInArray(items, id, parentKey, childKey, nextValue) {
if (!Array.isArray(items)) {
throw new TypeError("Expected items to be an array.");
}
return items.map((item) => {
if (item?.id !== id) {
return item;
}
const currentNested =
item[parentKey] !== null && typeof item[parentKey] === "object"
? item[parentKey]
: {};
return {
...item,
[parentKey]: {
...currentNested,
[childKey]: nextValue
}
};
});
}
// Example usage:
const profiles = [
{ id: "p1", preferences: { theme: "light", compact: false } }
];
const updatedProfiles = setNestedPropertyInArray(
profiles,
"p1",
"preferences",
"theme",
"dark"
);
console.log(updatedProfiles[0].preferences.theme); // "dark"
console.log(profiles[0].preferences.theme); // "light"
- Avoid direct mutation in reactive state: Assigning
targetObj.prop = valinside.forEach()or.find()mutates state in place, which can skip re-renders in React or cause subtle bugs in cached data. - Clone nested levels when needed: Every nested object layer that changes should be shallow-copied along the path to the updated property.
TL;DR: Use items.map((item) => match(item) ? { ...item, [prop]: value } : item) to update an object’s property inside an array non-mutatingly, spreading any nested objects along the path if updating nested fields.
