javascript - How to create duplicate object -


i have object nested objects in following way.

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

i created duplicate object using object in following way.

var h=object.create(g); 

the problem was,if modify in h,g reflecting.how can prevent this.i tried 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 modify in h,g should not reflect.

can me.

thanks.

as per _.clone docs,

create shallow-copied clone of object. nested objects or arrays copied reference, not duplicated.

shallow copied objects tend show problem experiencing now. if object use doesn't have methods/variables attached it, can this

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

this deep copy.

note: if object has circular references, make use of technique described in this answer


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -