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
}
1
  • 1
    obj.prop = 2 modifies the object in the array, since obj is a reference to the same object, not a clone. Commented Jan 5, 2020 at 12:17

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Or just .map((obj) => ({ ...obj, prop: 2 })), but it's worth noting this is a shallow copy.
Ah that's a great use of the spread operator. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.