3

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
}
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Tonald Drump
  • 1,227
  • 1
  • 19
  • 32
  • 1
    `obj.prop = 2` modifies the object in the array, since `obj` is a reference to the same object, not a clone. – VLAZ Jan 05 '20 at 12:17

1 Answers1

3

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); 
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
norbitrial
  • 14,716
  • 7
  • 32
  • 59