why a js map on an array modify the original array?

前端 未结 4 1779
走了就别回头了
走了就别回头了 2020-12-01 03:09

I\'m quite confuse by the behaviour of map().

I have an array of objects like this :

const products = [{
    ...,
    \'productType\' = \'premium\',         


        
4条回答
  •  我在风中等你
    2020-12-01 03:25

    Unfortunately, whether the spread operator nor the object assign operator does a deep copy.... You need to use a lodash like function to get areal copy not just a reference copy.

    const util = require('util');
    const print = (...val) => {
        console.log(util.inspect(val, false, null, false /* enable colors */));
    };
    const _ = require('lodash');
    
    const obj1 =     {foo:{bar:[{foo:3}]}};
    const obj2 =     {foo:{bar:[{foo:3}]}};
    
    const array = [obj1, obj2];
    
    const objAssignCopy = x => { return Object.assign({}, x, {})};
    const spreadCopy = x => { return {...x}};
    const _Copy = x => _.cloneDeep(x);
    
    const map1 = array.map(objAssignCopy);
    const map2 = array.map(spreadCopy);
    const map3 = array.map(_Copy);
    
    print('map1', map1);
    print('map2', map2);
    print('map3', map3);
    obj2.foo.bar[0].foo = "foobar";
    print('map1 after manipulation of obj2', map1); // value changed 
    print('map2 after manipulation of obj2', map2); // value changed
    print('map3 after manipulation of obj2', map3); // value hasn't changed!
    

提交回复
热议问题