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

Discussions

angular - Replacing value in an Array in typescript - Stack Overflow
Yeah, just realized the array is an array of object, and since those are references the new array is different but the items it refers to are the same. Totally logic. More on stackoverflow.com
🌐 stackoverflow.com
Replacing objects in array
I needed something were I have an array and I want to push another object onto that array if the object is not present in the array. I was using some to find if the object was present or not, if not I would push the object, but now my object is getting updated and should be updated on the arrray ... More on stackoverflow.com
🌐 stackoverflow.com
September 27, 2019
angular - Typescript - replace value in an array object - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Tried two ways to get partial summary within each array object, but failed. More on stackoverflow.com
🌐 stackoverflow.com
Replace array in object with object in TypeScript - Stack Overflow
I have a huge JSON that I need to load. I'm trying to reduce the size of it by using arrays within the objects, but I don't find a proper way to back-translate it in Typescript. Instead of repeatin... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › e707734830f5709a494c697e672f7647
Typescript find and replace an element in array · GitHub
Typescript find and replace an element in array · Raw · typescript-array-find-and-replace.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Dirask
dirask.com › posts › TypeScript-replace-element-in-array-DNAbK1
TypeScript - replace element in array
In TypeScript it is not intuitive at first time how to replace element in array. Replace operation can be achieved with Array.prototype.splice method. This arti...
🌐
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)
🌐
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.
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});
}
Find elsewhere
🌐
Webdevtutor
webdevtutor.net › blog › typescript-how-to-replace-element-in-array
How to Replace an Element in an Array in TypeScript
In this guide, we will explore different methods to efficiently replace elements in an array using TypeScript.
🌐
GeeksforGeeks
geeksforgeeks.org › 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
February 2, 2024 - 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.
🌐
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.
🌐
Refactoring.Guru
refactoring.guru › home › techniques › organizing data
Replace Array with Object
January 1, 2026 - Don’t forget to also create the object itself in the place where you initiated the data array. In the new class, create access methods one by one for each of the array elements. Give them self-explanatory names that indicate what they do. At the same time, replace each use of an array element in the main code with the corresponding access method.
🌐
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 - Using the indexOf() method finds the index of an element in an array, allowing you to perform operations based on its presence or absence. ... const arr = ['a', 'b', 'c']; const idx = arr.indexOf('a'); if (idx !== -1) { arr[idx] = 'z'; } ...
🌐
Stack Overflow
stackoverflow.com › questions › 74801798 › replace-array-in-object-with-object-in-typescript
Replace array in object with object in TypeScript - Stack Overflow
In the case that you would want to do this I would do, rows.map(row => { const object = { ...row }; columns.forEach((key, i) => object[key] = row.values[i]; return object }); 2022-12-14T17:13:33.49Z+00:00
🌐
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 - This article demonstrates how to replace an object in an array in JavaScript using the index and splice method with examples.
🌐
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 - The splice() method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-find-and-replace-in-array
Efficient Find and Replace in Arrays using TypeScript
In this code snippet, we are replacing the element 'cherry' with 'orange' in the fruits array using the map function. If you want to replace elements based on their index position, you can leverage the splice method in TypeScript: