How to clone a Javascript Array of Objects?

后端 未结 7 1321
一向
一向 2020-12-09 19:10

I have a result set which is an array of objects. I need to clone this so I can make changes to it, without touching the original data.

var data = w2ui.grid.         


        
相关标签:
7条回答
  • 2020-12-09 20:06

    You can achieve this from ES6 spread operators

    var arr1 = [1]
    var arr2 = arr1
    arr1 === arr2 //true
    arr2.push(2)
    arr2  //[1, 2]
    arr1  //[1, 2]
    var arr3 = [...arr1]  //create a copy of existing array
    arr1 === arr3  //false
    arr2 === arr3  //false
    arr3.push(3)
    arr3  //[1, 2, 3]
    arr1  //[1, 2]
    arr2  //[1, 2]
    

    Same syntax can be used for javascripts object as well

    var newObj = [...existingObj]

    0 讨论(0)
提交回复
热议问题