I am using .map() on an array inside a function. I am not modifying the array itself (arr = arr.map(...)), but rather creating a new array (var arr2 = arr.map(...)).
Yet, this still modifies the original arr outside my function (which I don't want). How can I preserve?
var arr = [{prop: 1}];
myFunction(arr);
console.log(arr[0].prop); // returns 2, I want it to return 1
function myFunction(arr) {
var arr2 = arr.map(obj => {
obj.prop = 2;
return obj;
});
console.log(arr[0].prop); // returns 2
}
It modifies based on its reference. If you want to create a new object and modify its properties then you need to use Spread Syntax. Read the documentation:
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
You can try the following:
var arr = [{prop: 1}];
myFunction(arr);
function myFunction(arr) {
var arr2 = arr.map(obj => {
let copyObj = {...obj};
copyObj.prop = 2;
return copyObj;
});
console.log(arr[0].prop);
console.log(arr2[0].prop);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With