Lodash has a deepClone method. I think that should be much better than mine.
https://lodash.com/docs/#cloneDeep
It supports all kind of features and can also clone complex structures. But it is slower compared to JSON.
The library owner describes it here:
You can install lodash to your project with:
npm i -S lodash
npm i -D @types/lodash
There is also a smaller version
npm i -S lodash.clonedeep
But i don’t know if the types are working for it.
It really depends on what you are doing. If you know exactly the data structure and it is not that big, I would use the spread operator for cloning, if performance is very important.
const obj = {
a: {
b: {
c: {
d: 'd',
dd: 'dd'
},
cc: 'cc'
},
bb: 'bb'
},
aa: 'aa'
};
const objCopy = {
...obj,
a: {
...obj.a,
b: {
...obj.a.b,
c: {
...obj.a.b.c,
}
}
}
};