0

I have one object

var a = {b:{c:{d:{e:1}}}}

I want to copy that object to another variable b, without passing a reference, so I try spread operator

var b = {...a}

It is not removing reference at a deep level, as I change the value in the object "a" it also changes the value in the object "b"

    a.b.c.d.e = 2
    console.log(b.b.c.d.e) 

it give output 2 instead of 1

var a = {b:{c:{d:{e:1}}}};
var b = {...a};
a.b.c.d.e = 2;
console.log(b.b.c.d.e)
document.write(b.b.c.d.e)

How can I handle this issue

GAURAV
  • 647
  • 6
  • 18

1 Answers1

0

I've always done this to copy JSON objects. Works great IMO there may be a better way out there.

var a = {b:{c:{d:{e:1}}}};
var b = JSON.parse(JSON.stringify(a));
a.b.c.d.e = 2;
console.log(b.b.c.d.e)
document.write(b.b.c.d.e)
Matthew
  • 3,136
  • 3
  • 18
  • 34
  • 1
    `stringy` should be `stringify`. Also this approach fails for dates, undefineds, regular expressions, functions, etc. etc. Use with care! – Ray Toal Sep 28 '19 at 07:23
  • 1
    Thanks for catching that grammar mishap. It is fixed now in the answer. I know the undefined value will just not exist when it gets parse, but when checking against to see if a value is stored, it returns the same; granted it does lose the key value if that is checked against. Also, you don't lose dates, just the date object itself, however, regular expressions are just dropped. – Matthew Sep 28 '19 at 07:29