Replacing values in a JSON array depends on whether you know the exact index of the item or if you need to search for it based on a property.
Doing it wrong can mutate your original data or break the structure entirely. Let's look at the right way to do it.
1. Replacing by Index
If you know exactly which item in the array you want to change, you can target it directly by its index.
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
// Replace the second item entirely
users[1] = { id: 2, name: "Robert" };
2. Replacing a Property in an Object (using map)
If you want to keep the array structure but update a specific property across all items, use map(). This creates a new array, which is best practice if you want to avoid mutating the original data.
const updatedUsers = users.map(user => {
if (user.id === 2) {
return { ...user, name: "Robert" };
}
return user;
});
3. Finding and Replacing in Deeply Nested Arrays
If your JSON has arrays inside objects inside arrays, a simple .map() won't be enough. You need a recursive function to traverse the entire structure and replace the value wherever it's found.
function replaceDeep(obj, target, replacement) {
if (Array.isArray(obj)) {
return obj.map(item => replaceDeep(item, target, replacement));
} else if (obj !== null && typeof obj === 'object') {
const newObj = {};
for (const key in obj) {
newObj[key] = replaceDeep(obj[key], target, replacement);
}
return newObj;
}
// If the current value matches the target, replace it
return obj === target ? replacement : obj;
}
Common Gotchas
-
Reference vs Value: If you are replacing objects, make sure you are creating a new object (
{ ...obj }) rather than just modifying the reference, or you might accidentally mutate the original JSON. -
Regex vs String: Simple
.replace()only replaces the first match in a string. If you want to replace all occurrences, you need a global regex (/target/g). -
Null values: Remember that
typeof null === 'object', so you must check forobj !== nullbefore recursing.
The Visual Way
Writing recursive scripts is fine for code, but if you just need to replace a specific value or pattern across a massive JSON payload once, writing a script is overkill.
If you want to find and batch replace targeted values, patterns, or data types across nested JSON visually, I built a free JSON Value Replacer.
100% client-side. Nothing uploaded.
Have you ever accidentally mutated a JSON object and spent hours debugging it? Let me know in the comments.
Top comments (0)