Object array assigned to another array, how to keep the original array unchanged when manipulating the new array

var c = self.threeData1;
                                        var threeData2 = c.concat();
                                        
                                         threeData2.forEach(function(iten){
                                            iten.price = "---"
                                         })
                                       console.log("c",c)
                                       console.log("threeData2",threeData2)
May.22,2021

because the object assignment, they point to the same application, so it will change.


    The elements in the
  1. original array treeData1 are all object, that is, reference types.
  2. The concat method merges two arrays, similar to assigning object1 to object2 . At this time, modify the attribute a of object1 , and the a attribute of object2 is the same as the an attribute of object1 .

so the attribute of an element in the first array is modified, and the corresponding element attribute in the new array is also modified.

To sum up,

is the problem of copying / cloning value type data and reference type data.
when referencing type data assignments, it is a pointer to this object, not an object stored in the heap.


my Baidu


Deep copy, you can use JSON.parse (JSON.stringify (arr)) to achieve deep copy). You can learn about the disadvantages of this method by yourself


. When assigning values to

arrays, use the cloneDeep method of lodash .

var arr2 = cloneDeep(arr1)

or other methods that can be copied deeply:
https://codeshelper.com/a/11.

in the final analysis, when the array directly assigns , the address of the new array and the original array will point to the same memory address, so if you change the original array, the new array will also be changed.

Menu