How to clone a Javascript Array of Objects?

后端 未结 7 1320
一向
一向 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 19:43

    EDIT

    Deep clone use JSON.parse(JSON.stringify(arr));

    Shallow clone Use slice(0);

    var arr = [{'obj1':1}, {'obj2':2}];
    var clone = arr.slice(0);
    console.log(clone);

    var arr = [{'obj1':1}, {'obj2':2}]
    var clone = JSON.parse(JSON.stringify(arr));
    console.log(clone);

    0 讨论(0)
  • 2020-12-09 19:47

    Since you are using jquery you can try extend:

    var arr = [{'obj1':1}, {'obj2':2}];
    var clone = jQuery.extend(true, [], arr);
    clone[0]['obj1']=10;
    console.log(clone);
    console.log(arr);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    0 讨论(0)
  • 2020-12-09 19:54

    This is because an array is held as a pointer, so setting a new variable just points to the same array.

    The easiest way I know of is with slice...

    var data = w2ui.grid.records.slice(0);
    

    This creates a new array with all of the original values in, because you're slicing from the first one (0).

    If you need a deep clone, because your array contains objects/arrays too, try this...

    https://github.com/pvorb/clone

    0 讨论(0)
  • 2020-12-09 20:05

    Lodash has a method specifically for this called clonedeep. There's a standalone package for it if you don't want to pull in the entire library:

    https://www.npmjs.com/package/lodash.clonedeep

    0 讨论(0)
  • 2020-12-09 20:06

    ES6:

    If you want to have cloned objects too, you have to spread array and objects:

    const newArrayOfObjects = [
      ...originalArrayOfObject
    ].map(i => ({ ...i}));
    
    0 讨论(0)
  • 2020-12-09 20:06

    There are various ways to do it-

    let arr = [{
      'obj1': 1
    }, {
      'obj2': 2
    }];
    
    // 1
    const arr2 = arr.slice();
    console.log(arr2);
    
    // 2
    const arr3 = [].concat(arr);
    console.log(arr3);
    
    // 3
    // or use the new ES6 Spread
    const arr4 = [...arr];
    console.log(arr4);
    
    // 4
    const arr5 = Array.from(arr);
    console.log(arr5);

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