You can use Array#map with Array#find.

arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

Show code snippet

var arr1 = [{
    id: '124',
    name: 'qqq'
}, {
    id: '589',
    name: 'www'
}, {
    id: '45',
    name: 'eee'
}, {
    id: '567',
    name: 'rrr'
}];

var arr2 = [{
    id: '124',
    name: 'ttt'
}, {
    id: '45',
    name: 'yyy'
}];

var res = arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

console.log(res);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Here, arr2.find(o => o.id === obj.id) will return the element i.e. object from arr2 if the id is found in the arr2. If not, then the same element in arr1 i.e. obj is returned.

Answer from Tushar on Stack Overflow
Top answer
1 of 16
295

You can use Array#map with Array#find.

arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

Show code snippet

var arr1 = [{
    id: '124',
    name: 'qqq'
}, {
    id: '589',
    name: 'www'
}, {
    id: '45',
    name: 'eee'
}, {
    id: '567',
    name: 'rrr'
}];

var arr2 = [{
    id: '124',
    name: 'ttt'
}, {
    id: '45',
    name: 'yyy'
}];

var res = arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

console.log(res);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Here, arr2.find(o => o.id === obj.id) will return the element i.e. object from arr2 if the id is found in the arr2. If not, then the same element in arr1 i.e. obj is returned.

2 of 16
14

There is always going to be a good debate on time vs space, however these days I've found using space is better for the long run.. Mathematics aside let look at a one practical approach to the problem using hashmaps, dictionaries, or associative array's whatever you feel like labeling the simple data structure..

    var marr2 = new Map(arr2.map(e => [e.id, e]));
    arr1.map(obj => marr2.has(obj.id) ? marr2.get(obj.id) : obj);

I like this approach because though you could argue with an array with low numbers you are wasting space because an inline approach like @Tushar approach performs indistinguishably close to this method. However I ran some tests and the graph shows how performant in ms both methods perform from n 0 - 1000. You can decide which method works best for you, for your situation but in my experience users don't care to much about small space but they do care about small speed.



Here is my performance test I ran for source of data

var n = 1000;
var graph = new Array();
for( var x = 0; x < n; x++){
  var arr1s = [...Array(x).keys()];
  var arr2s = arr1s.filter( e => Math.random() > .5);
  var arr1 = arr1s.map(e => {return {id: e, name: 'bill'}});
  var arr2 = arr2s.map(e => {return {id: e, name: 'larry'}});
  // Map 1
  performance.mark('p1s');
  var marr2 = new Map(arr2.map(e => [e.id, e]));
  arr1.map(obj => marr2.has(obj.id) ? marr2.get(obj.id) : obj);
  performance.mark('p1e');
  // Map 2
  performance.mark('p2s');
  arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);
  performance.mark('p2e');
  graph.push({ x: x, r1: performance.measure('HashMap Method', 'p1s', 'p1e').duration, r2: performance.measure('Inner Find', 'p2s','p2e').duration});
}
🌐
DEV Community
dev.to › albertomontalesi › find-and-replace-elements-in-array-with-javascript-2e4n
Find and Replace elements in Array with JavaScript - DEV Community
May 10, 2021 - Next up are two new metho introduced in ES6 (ES2015): const arr = [1,2,3,4,5]; arr.some((el) => el === 2); // true arr.every((el) => el === 3); // false · Array.some will check if at least one value in the array matches the condition in our callback function and Array.every will check that ALL of the elements in the Array match that condition. Now that we know how to check if the Array includes a specific element, let's say we want to replace that element with something else.
Discussions

javascript - Find and replace object in array (based on id) - Stack Overflow
Got a bit of a puzzle here...I want to loop through allItems and return allItems but replace with any newItems that matches its id. How can I look for a match on id and then replace it with the cor... More on stackoverflow.com
🌐 stackoverflow.com
February 26, 2019
javascript - How to find and replace an object with in array of objects - Stack Overflow
Find object by id in an array of JavaScript objects · EDIT: Forgot about the replacement piece. More on stackoverflow.com
🌐 stackoverflow.com
How do I replace all object values in an array with values from another array?
Yeah, it's pretty simple: const result = data.map(obj => ({ ...obj, code_block: obj.code_block.match(/result:.+/)[0] })) More on reddit.com
🌐 r/learnjavascript
7
21
December 27, 2022
javascript - How can I find and update values in an array of objects? - Stack Overflow
You're just adding the item to the original array filtered of the item you're replacing. ... This way will not update the item in place, so original order is changed. 2022-07-27T10:01:31.117Z+00:00 ... Save this answer. ... Show activity on this post. Whereas most of the existing answers are great, I would like to include an answer using a traditional for loop, which should also be considered here. The OP requests an answer which is ES5/ES6 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Peterbe.com
peterbe.com › plog › replace-an-item-in-an-array-without-mutation-in-javascript
Replace an item in an array, by number, without mutation in JavaScript (ES6) - Peterbe.com
And now you want to replace that second item ("J" instead of "M") and suppose that you already know its position as opposed to finding its position by doing an Array.prototype.find. ... const index = 1; const replacementItem = "J"; const newArray = Object.assign([], items, {[index]: replacementItem}); console.log(items); // ["B", "M", "X"] console.log(newArray); // ["B", "J", "X"]
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › splice
Array.prototype.splice() - JavaScript - MDN Web Docs
July 10, 2025 - To create a new array with a segment removed and/or replaced without mutating the original array, use toSpliced().
🌐
JsCraft
js-craft.io › home › javascript – find and replace an object in array
Javascript – find and replace an object in array
November 30, 2023 - If we have a homogeneous object structure of the array we can just compare the elements in the array based on a specific field: const myArray = [ {id: 100, name: "Dan"}, {id: 101, name: "Bob"}, {id: 102, name: "Joe"}, ] const searchedObj = {id: 101, name: "Bob"} const replacingObj = {id: 105, name: "Todd"} const i = myArray.findIndex(x => x.id === searchedObj.id) myArray[i] = replacingObj console.log(myArray)
🌐
IQCode
iqcode.com › code › javascript › find-and-replace-value-in-array-of-objects-javascript
find and replace value in array of objects javascript Code Example
September 27, 2021 - let arr = [ { &quot;enabled&quot;: true, &quot;deviceID&quot;: &quot;eI2K-6iUvVw:APA&quot;, }, { &quot;enabled&quot;: true...
🌐
Delft Stack
delftstack.com › home › howto › javascript › replace object in array javascript
How to Replace Object in an Array in JavaScript | Delft Stack
February 2, 2024 - In the output, the element June is replaced by the new element May at index 4. This is how we can use the splice() method to replace any object in an array in JavaScript.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-replace-an-object-in-an-array-with-another-object-based-on-property
How to Replace an Object in an Array with Another Object Based on Property ? - GeeksforGeeks
July 23, 2025 - This method used the map function to create a new array by iterating over the original array. It checks a specific property to identify the target object for replacement.
🌐
Reddit
reddit.com › r/learnjavascript › how do i replace all object values in an array with values from another array?
r/learnjavascript on Reddit: How do I replace all object values in an array with values from another array?
December 27, 2022 -

Let's say I have an array called data and it contains the following:

data: [
    {
        id: 100,
        name: "something",
        code_block: "x\ny\nz\na\nresult:touchdown\nasd\n"
    },
    {
        id: 200,
        name: "somethingElse",
        code_block: "a\nb\nc\nd\nresult:touchdown\nasd\n"
    }
]

What I'm trying to do is iterate through the code_block property to extract out a string (result:touchdown) and replace the original value of code_block with that string. The problem is I'm not sure how I can perform the array methods like .map and such and still carry over the id and name properties.

Would you guys recommend that I make a shallow copy of the data object, iterate through code_block, and then replace that property on the original data object with the new array? Is there even a way to do this, or is there a better approach to what I'm doing here?

Thanks in advance for all your help!

🌐
CodeSpeedy
codespeedy.com › home › replace an object in an array with another object in javascript
Replace an object in an array with another object in JavaScript
February 16, 2024 - We can replace an object in an array with another object in JavaScript using splice() method as well as map() method.
🌐
Planeta-nk
planeta-nk.ru › post › javascript find and replace object in array es6
Just a moment...
This process is automatic. Your browser will redirect to your requested content shortly · Please wait a few seconds
Top answer
1 of 12
475

You can use findIndex to find the index in the array of the object and replace it as required:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;

This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:

items.forEach((element, index) => {
    if(element.id === item.id) {
        items[index] = item;
    }
});
2 of 12
107

My best approach is:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

items[items.findIndex(el => el.id === item.id)] = item;

Reference for findIndex

And in case you don't want to replace with new object, but instead to copy the fields of item, you can use Object.assign:

Object.assign(items[items.findIndex(el => el.id === item.id)], item)

as an alternative with .map():

Object.assign(items, items.map(el => el.id === item.id? item : el))

Functional approach:

Don't modify the array, use a new one, so you don't generate side effects

const updatedItems = items.map(el => el.id === item.id ? item : el)

Note

Properly used, references to objects are not lost, so you could even use the original object reference, instead of creating new ones.

const myArr = [{ id: 1 }, { id: 2 }, { id: 9 }];
const [a, b, c] = myArr;
// modify original reference will change object in the array
a.color = 'green';
console.log(myArr[0].color); // outputs 'green'

This issue usually happens when consuming lists from database and then mapping the list to generate HTML content which will modify the elements of the list, and then we need to update the list and send it back to database as a list.

Good news is, references are kept, so you could organize your code to get advantage of it, and think about a list as an Object with identities for free, which are integers from 0 to length -1. So every time you access any property of your Object, do it as list[i], and you don't lose reference, and original object is changed. Keep in mind that this is useful when your source of truth is only one (the Object created), and your app is always consistently consuming the same Object (not fetching several times from database and assigning it to list along the lifespan of the component).

Bad news is that the architecture is wrong, and you should receive an object by ids (dictionary) if this is what you need, something like

{ 
  1232: { id: 1232, ...},
  asdf234asf: { id: 'asdf234asf', ...},
  ...
}

This way, you don't search in arrays, which is resource consuming. You "just access by key in the object", which is instant and performant.

🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › replace or append array value
Replace or append a value in a JavaScript array - 30 seconds of code
March 23, 2024 - const replaceOrAppend = (arr, val, compFn) => { const res = [...arr]; const i = arr.findIndex(v => compFn(v, val)); if (i === -1) res.push(val); else res.splice(i, 1, val); return res; }; const people = [ { name: 'John', age: 30 }, { name: 'Jane', age: 28 }, ]; const jane = { name: 'Jane', age: 29 }; const jack = { name: 'Jack', age: 28 }; replaceOrAppend(people, jane, (a, b) => a.name === b.name); // [ { name: 'John', age: 30 }, { name: 'Jane', age: 29 } ] replaceOrAppend(people, jack, (a, b) => a.name === b.name); // [ // { name: 'John', age: 30 }, // { name: 'Jane', age: 28 }, // { name: 'Jack', age: 28 } // ] ... Easily remove duplicates from a JavaScript array using the built-in Set object, and learn a few other tricks along the way.