I'm using angularjs and it took me some time to find out how to copy an object to another object. Normally you'll get an objects clone by calling clone or here in angular copy:

var targetObj = angular.copy(sourceObj);

This gives you a new cloned instance (with a new reference) of the source object. But a quick look into the docs reveals the second parameter of copy:

angular.copy(sourceObj, targetObj)

This way you can override a target object with the fields and methods of the source and also keep the target objects reference.

Answer from schmijos on Stack Overflow
🌐
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 ...
Discussions

javascript - Replacing objects in array - Stack Overflow
I am only submitting this answer ... order of objects. I recognize that it is not the most efficient way to accomplish the goal. Having said this, I broke the problem down into two functions for readability. Copy// The following function is used for each itertion in the function updateObjectsInArr const newObjInInitialArr = ... More on stackoverflow.com
🌐 stackoverflow.com
How to replace object key value by another key value in the same object ?
let newlist = list.map(e => ({...e, name: e.nationality}) )
  • e is for "element", where the .map method touches each element in a source array, and then returns a new array.

  • newlist will have your modified array. list remains unchanged.

  • e => begins an "arrow function". I want to return an object, but objects require curly braces, just like a function body. Defining an object {} and wrapping it in () sentinels tells JS that "these curlies are not a function body"

  • without a function body, the "arrow function" expects a statement which it will then return by default without specifically using return keyword.

  • ...e does a js "spread" on the e variable. It takes the entire contents of e and puts them right there as part of the new object. It then replaces the contents of the name property with data from the current element.

The long way:

let newlist = list.map(function (element) {
	element.name = element.nationality
	return element
})
More on reddit.com
🌐 r/learnjavascript
2
5
September 7, 2022
How do you replace an Object value in Javascript? - Stack Overflow
Here's the question: Create a function called changeEmail that takes in a user object and a newEmail string. Replace the user's current email address (assigned to the email property) with the newEmail string, then return the updated user object. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Array of objects, replace an object with a new object - Stack Overflow
I have an array of objects that represents the data of my model at any given time (a group of form controls on the stage of my app). The visual for this array of objects is attached here: In this e... More on stackoverflow.com
🌐 stackoverflow.com
February 1, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-replace-an-object-in-an-array-with-another-object-based-on-property-2
How to Replace an Object in an Array with Another Object Based on Property ? | GeeksforGeeks
February 27, 2024 - You can use filter() to create a new array containing only the elements that don't match the desired object, and then use concat() to merge the new object with the filtered elements.
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});
}
🌐
Itsourcecode
itsourcecode.com › home › how to find and replace object in an array javascript?
How to Find and Replace Object in an Array JavaScript?
September 6, 2023 - ... Replacing an object in an array in JavaScript can be achieved through various methods, such as using the map() method, the splice() method, or a for loop with the splice method.
Find elsewhere
🌐
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 - Suppose we want to replace the first two objects with different colors names in the array. We can do that using the index of these objects. At index 0, we have Red, and at index 1, we have Blue. We can replace these two colors using selectedColors[], give the index number of the object we want to replace, and assign a new color.
🌐
W3Resource
w3resource.com › javascript › object-property-method › string-replace.php
JavaScript replace() Method : String Object - w3resource
<![CDATA[ regex = /brown/gi; str1 = "The Quick Brown Fox Jumps Over The Lazy Dog"; document.write("Original string : "+str1+"<br />"); document.write("Searched string : brown"+"<br />"); document.write("New string : white "+"<br />"); newstr=str1.replace(regex, "white"); document.write(newstr) //]]> </script> </body> </html> View the example in the browser · Supported Browser · See also: JavaScript Core objects, methods, properties. Previous: JavaScript match() Method: String Object Next: JavaScript search() Method: String Object · Test your Programming skills with w3resource's quiz.
🌐
GitHub
gist.github.com › flipace › bed6b89aed5cb0e19cde
Deep replace a value within an object or array (using lodash or underscore) · GitHub
JSON.parse(JSON.stringify(object), (key, value) => { if (key=='propToChange') { return newValue; } else { return value; } }) ... FYI: You can do it with lodash like this: _.cloneDeepWith(object, value => value === prevVal ?
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-replace-the-names-of-multiple-object-keys-with-the-values-provided-using-javascript
How to replace the names of multiple object keys with the values provided using JavaScript ? | GeeksforGeeks
January 12, 2022 - In this approach we will directly pick up the object key and will change the name of that picked key with the name provided by the user. After providing the key name we will then delete the previously declared one and replace it with new one.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › assign
Object.assign() - JavaScript - MDN Web Docs
The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
🌐
JsCraft
js-craft.io › home › javascript – find and replace an object in array
Javascript – find and replace an object in array
November 30, 2023 - for(let i = 0; i < myArray.length; i++) { if(deepEqual(myArray[i], searchedObj.id)) { myArray[i] = replacingObj } } And this concludes our example. If you are interested be sure to check also how the array reduce() function works in Javascript.
🌐
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...