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?

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.