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});
}
🌐
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.
Discussions

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
Add/Replace object from array of objects JavaScript - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I want to Add/Replace the object from array of objects by testing some properties against array object More on stackoverflow.com
🌐 stackoverflow.com
February 12, 2018
javascript - How to replace item in array? - Stack Overflow
Simple method, however, it always loops through the entire array of objects, to only replace a single item. More on stackoverflow.com
🌐 stackoverflow.com
Replace item in array of objects with Javascript - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. ... I want to replace this new object for the one with the same ID in the original array, how can I do this? More on stackoverflow.com
🌐 stackoverflow.com
December 9, 2020
🌐
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!

🌐
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 - If the index is found, the splice function is used to replace the existing object with a new one. This approach directly modifies the original array. Example: Demonstration to find the index of the element based on the property using findIndex ...
🌐
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...
Find elsewhere
🌐
The Web Dev
thewebdev.info › home › how to replace objects in array with javascript?
How to replace objects in array with JavaScript? - The Web Dev
June 5, 2022 - To replace objects in array with JavaScript, we can use the array map method. How to merge duplicate objects in array of objects with JavaScript?
🌐
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 - JavaScript program to replace an object in an array with another object using map() method and conditional statement. const myArray = [ {name: 'Sam', age: 24}, {name: 'Rayan', age: 26} ]; //Defining the object by which we want to replace const ...
🌐
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 - As you can see, using findIndex we can easily find and then replace Objects in an Array of Objects.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-replace-element-in-array
How to Replace an Element in an Array in JavaScript | bobbyhadz
The forEach() method is useful if you need to replace all occurrences of the value in the array. You can learn more about the related topics by checking out the following tutorials: Filter an Array with Multiple Conditions in JavaScript · Filter ...
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-replace-an-item-from-an-array-in-javascript
JavaScript - Replace an Item from JS Array - GeeksforGeeks
July 12, 2025 - The splice() method in JavaScript is another way to replace items in an array. This method allows you to remove items and insert new ones at the specified position in the array. Note: Splice() method deletes zero or more elements of an array ...
🌐
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
Here's how you do it: 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"] Wasn't immediately obvious ...