Js Array.prototype.map() happens to be mutable?

一曲冷凌霜 提交于 2021-02-07 12:54:05

问题


Why would the map method mutate the original array when its initial purpose is to create a new array ?

I have an array of object which I pass to a pure function which in turn maps the given array and return a new one. Then I notice that the original array was also changed.. I understand the concept that Object in Js are passed by reference and all but still cant quite grab why would the implementation of map would mutate the original array, kinda beats the purpose IMO.

var initialArray = [ { name: 'one' }, { name: 'two' }, { name: 'three'} ];

function doSomething(array) {

  // lodash
  // return _.map(array, (item) => _.assign(item, {isSelected: true}));  

  // vanilla
  return array.map(function(item) {
    item['isSelected'] = true;
    return item
  });

}

var changedArray = doSomething(initialArray);

console.log('initialArray', initialArray); // [{ name: 'one', isSelected: true }, ...]
console.log('changedArray', changedArray); // [{ name: 'one', isSelected: true }, ...]
console.log(initialArray === changedArray); // false

First Id like to understand why this happens ?

Second Id like to understand how would one map an array without changing the original one ? (ie. doing ._cloneDeep each time before map feels wrong)

Thanks in advance !

Edit

Ok so from what I understand this is how things just are. I think I might have had higher expectation for some reason, but it is explainable in Js so at least there is some consistency in place.

The most elegant solution I can think of for creating a new array with new members is

return _.map(array, (item) => _.assign({}, ...item, {isSelected: true}));   

回答1:


.map will create a new array, but the objects inside the array is still referenced.

so when you make changes in the object item inside .map function, it is referencing the original object in the input array.

one way to fix it is to clone the each object , before you modify it

var initialArray = [ { name: 'one' }, { name: 'two' }, { name: 'three'} ];

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

function doSomething(array) {

  // lodash
  // return _.map(array, (item) => _.assign(item, {isSelected: true}));  

  // vanilla
  return array.map(function(item) {
    var copy = clone(item);
    copy['isSelected'] = true;
    return copy;
  });

}

var changedArray = doSomething(initialArray);

console.log('initialArray', initialArray); // [{ name: 'one'}, ...]
console.log('changedArray', changedArray); // [{ name: 'one', isSelected: true }, ...]
console.log(initialArray === changedArray); // false

Credit : clone function is copied from this post




回答2:


your modifying the object that get's passed by reference to the map function, not the array that get's mapped. Both the changedArray and the initialArray contain the same object.

var initialArray = [ { name: 'one' }, { name: 'two' }, { name: 'three'} ];
var initialArray2 = [ { name: 'one' }, { name: 'two' }, { name: 'three'} ];

function doSomething(array) {
  // vanilla
  return array.map(function(item) {
    item['isSelected'] = true;
    return item
  });

}

function doSomethingElse(array){
  return array.map(function( item ){
    // return a new object don't change the initial one
    return { name: item.name, isSelected: true };
  });
}

var changedArray = doSomething(initialArray),
    differentObjectsInArray = doSomethingElse( initialArray2 );

console.assert( initialArray !== changedArray, 'both arrays are different' );
console.assert( initialArray[0] !== changedArray[0], 'both arrays are referencing different objects' );
console.assert( initialArray2[0] !== differentObjectsInArray[0], 'both arrays are referencing different objects' );
console.log('initialArray', initialArray );
console.log('initialArray2', initialArray2 );
console.log('differentObjectsInArray', differentObjectsInArray );
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>



回答3:


With ES6:

let newArray = [...oldArray].map(doStuff);



回答4:


 var targetArray=JSON.parse(JSON.stringify(souceArray));


来源:https://stackoverflow.com/questions/34716651/js-array-prototype-map-happens-to-be-mutable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!