Deep copy an array in Angular 2 + TypeScript

前端 未结 10 1028
温柔的废话
温柔的废话 2020-11-27 04:33

I have an array of objects that is an input. Lets call it content.

When trying to deep copy it, it still has a reference to the previous array.

相关标签:
10条回答
  • 2020-11-27 05:09

    The only solution I've found (almost instantly after posting the question), is to loop through the array and use Object.assign()

    Like this:

    public duplicateArray() {
      let arr = [];
      this.content.forEach((x) => {
        arr.push(Object.assign({}, x));
      })
      arr.map((x) => {x.status = DEFAULT});
      return this.content.concat(arr);
    }
    

    I know this is not optimal. And I wonder if there's any better solutions.

    0 讨论(0)
  • 2020-11-27 05:14

    Here is my own. Doesn't work for complex cases, but for a simple array of Objects, it's good enough.

      deepClone(oldArray: Object[]) {
        let newArray: any = [];
        oldArray.forEach((item) => {
          newArray.push(Object.assign({}, item));
        });
        return newArray;
      }
    
    0 讨论(0)
  • 2020-11-27 05:15

    Simple:

    let objCopy  = JSON.parse(JSON.stringify(obj));
    

    This Also Works (Only for Arrays)

    let objCopy2 = obj.slice()
    
    0 讨论(0)
  • 2020-11-27 05:15

    This is Daria's suggestion (see comment on the question) which works starting from TypeScript 2.1 and basically clones each element from the array:

    this.clonedArray = theArray.map(e => ({ ... e }));
    
    0 讨论(0)
  • 2020-11-27 05:17

    you can use use JQuery for deep copying :

    var arr =[['abc'],['xyz']];
    var newArr = $.extend(true, [], arr);
    newArr.shift().shift();
    
    console.log(arr); //arr still has [['abc'],['xyz']]
    
    0 讨论(0)
  • 2020-11-27 05:18

    Check this:

      let cloned = source.map(x => Object.assign({}, x));
    
    0 讨论(0)
提交回复
热议问题