json - JavaScript object assignment -
how result?
{"obj1": { "title": "title", "data": [1,2,3] }, "obj2": { "title": "title", "data": [4,5,6] }, "obj3": { "title": "title", "data": [7,8,9] }}
var obj = {title:'title'} var newobj = {}; newobj.obj1 = obj; newobj.obj2 = obj; newobj.obj3 = obj; newobj.obj1.data = []; newobj.obj1.data = [1,2,3]; newobj.obj2.data = []; newobj.obj2.data = [4,5,6]; newobj.obj3.data = []; newobj.obj3.data = [7,8,9]; console.log(json.stringify(newobj))
you're assigning obj
newobj
's properties. wouldn't assign new object properties means they're referencing obj
. , when it's referenced, whenever make changes reference, other places referenced changes.
what need make copy of obj
, assign newobj
's proerties. ...
syntax in {}
creates new object obj
's properties.
var obj = {title:'title'} var newobj = {}; newobj.obj1 = { ...obj }; newobj.obj2 = { ...obj }; newobj.obj3 = { ...obj }; newobj.obj1.data = [1,2,3]; newobj.obj2.data = [4,5,6]; newobj.obj3.data = [7,8,9]; console.log(json.stringify(newobj));
wiki
Comments
Post a Comment