2

I have an object with nested objects like in the following way.

var g = {
    "steps": [{
        "location": [{
            "a": "1"
        }, {
            "a": "2"
        }]
    }]
};

I created duplicate object using Object like in the following way.

var h=Object.create(g);

The problem was,If I Modify anything in h,g also reflecting.How can I prevent this.I tried with underscore function(clone).

modified:

  h["steps"][0]["location"][0]["a"]="3"

After modify:

g looks like

enter image description here

h looks like

enter image description here

Even If I modify anything in h,g should not be reflect.

can anyone help me.

Thanks.

Community
  • 1
  • 1
user3279058
  • 549
  • 4
  • 7
  • 22

1 Answers1

4

As per the _.clone docs,

Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.

Shallow copied objects tend to show the problem you are actually experiencing now. If the object you use doesn't have any methods/variables attached to it, you can do this

var h = JSON.parse(JSON.stringify(g));

This does deep copy.

Note: If the object has circular references, then make use of the technique described in this answer

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Nice idea. Watch out for circular references though. And objects with non-standard prototypes. – Joe Mar 21 '14 at 10:23