4
dst = { "a" : 1}
src = { "edf" : {"zyx" : "right"}}
Object.assign(dst, src)
src.edf.zyx = "wrong"
console.log(dst["edf"]["zyx"])

I expect to see 'right' as the output but it prints 'wrong'.

It means, Object.assign has not done a deep copy of complex objects from source to destination. How can i do deep copy?

Note: i am aware of lodash.deepClone, but i am trying to avoid outside frameworks

1 Answers1

0

First I want to tell you that it's not bulletproof solution (in case of date object). If you want "right" as answer, here is your solution:

var dst,src = { "edf" : {"zyx" : "right"} };
dst = JSON.parse(JSON.stringify(src));
dst["a"] = 1;
src.edf.zyx = "wrong";
console.log(src, dst);

So please read these links to understand deep copy better

Most elegant way to clone a JavaScript object

Copy JavaScript object to new variable NOT by reference?

shaedrich
  • 5,457
  • 3
  • 26
  • 42
Rajan Singh
  • 611
  • 4
  • 9