Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does map mutate array of objects?

Tags:

javascript

Why does map mutate array of objects?

var obj = {
  items: [{
    value: 1,
    selected: true
  }, {
    value: 2,
    selected: false
  }]
};

var items = obj.items.map(i => {
  if (i.value === 2) i.selected = true;
  return i;
});

console.log(obj);
like image 429
terreb Avatar asked Jun 22 '18 14:06

terreb


People also ask

Does map mutate the array?

map() is a functional programming technique. It iterates through the elements of an array, transforms each member of that array, and returns a new array of the same size with the transformed members e.g. performing calculations on a list of numbers. It does not mutate the original data, it returns a new array.

Does map affect the array?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

Does map mutate object?

The map() method is a copying method. It does not alter this .

Does map method mutate an array in JavaScript?

map() method. .map() creates an array from calling a specific function on each item in the parent array. .map() is a non-mutating method that creates a new array, as opposed to mutating methods, which only make changes to the calling array.


1 Answers

If you want a quick solution for an unmutable version of .map over an array of objects you can use the spread operator:

myArrayOfObjects.map(({...obj}) => { });

Example:

const foo = [];

for(let i = 0; i < 5; i++) {
    foo.push({label: "foo"});
}

const bar = foo.map(({...val}) => {
    val.id = Math.random();
  return val;
});

console.log(foo);
console.log(bar);
like image 74
Manu Schiller Avatar answered Sep 17 '22 14:09

Manu Schiller