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.
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.
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;
}
Simple:
let objCopy = JSON.parse(JSON.stringify(obj));
This Also Works (Only for Arrays)
let objCopy2 = obj.slice()
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 }));
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']]
Check this:
let cloned = source.map(x => Object.assign({}, x));