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);
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.
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.
The map() method is a copying method. It does not alter this .
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.
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);
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