1

i need to clone array object in array object by use typescript for change some value in deep properties but when i clone it it reference at last

dokey(xData : any) {
        _.keys(xData).forEach((x: any) => {
            xData[x] = _.isArray(xData[x]) ? this.duplicateArray(xData[x]) : xData[x];
        });
        return xData;
    }

duplicateArray(content: Object[]) {
    let arr: any = [];
    content.forEach((x: any) => { 
        arr.push(Object.assign({}, this.dokey(x) ));
    })
    return arr;
}

mainFunc() {
    let var1: any = [{ a: [{ q: '99' }, { w: '98' }] }, { b: '2' }];
    let var2 = this.duplicateArray(var1);
    var2[0].a[0].q = 'a002';
    console.log(var1, var2);
}

it should be not duplicate but it duplicate

enter image description here

how can i do for deep clone it?

uopeydel
  • 431
  • 4
  • 22
  • 1
    Is your object JSON serializable? If so, you could call `JSON.parse(JSON.stringify(var1))` to clone it. – jrossi Apr 26 '17 at 17:16
  • Possible duplicate of [What is the most efficient way to deep clone an object in JavaScript?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – msanford Apr 26 '17 at 20:40

1 Answers1

1

If the original object is serializable you can simply do:

function deepcopy<T>(o: T): T {
  return JSON.parse(JSON.stringify(o));
}

Note that you cannot reliably copy some things e.g. functions (because they might capture variables in closures).

More

A video lesson on the same : https://egghead.io/lessons/typescript-deep-copy-aka-clone-objects-using-typescript

basarat
  • 261,912
  • 58
  • 460
  • 511