javascript - add array object into object -
var objectz = {}; objectz.a = 1; objectz.b = 2 objarr = json.parse(localstorage.getitem('myitem')); $.each(objarr, function(key,obj){ objectz.key = obj; } console.log(objectz);
i want add array value existing obj, got {1,2,10} 3 9 got override, mistake?
aside syntax errors (copy/paste error?), code iterating through objarr
, overwriting property literally called "key"
on objectz
(i.e. objectz.key
). not using function parameter iterator called key
. if wanted use function parameter called key update objectz
want use objectz[key]
.
it hard guess localstorage.getitem('myitem')
returns. assuming objarr = [{c: 3},{d: 4},{e: 5},{f: 6},{g: 7},{h: 8},{i: 9},{j: 10}]
, here corrected version of code:
http://jsbin.com/viwiko/edit?js,console
var objectz = {}; objectz.a = 1; objectz.b = 2; objarr = [{c: 3},{d: 4},{e: 5},{f: 6},{g: 7},{h: 8},{i: 9},{j: 10}]; //json.parse(localstorage.getitem('myitem')); //$.each(objarr, function(key,obj){ // objectz.key = obj;//overwrites property called 'key' each element of objarr //}); $.each(objarr, function(key,obj){ objectz[key] = obj;//key 0 based array index (i.e. 0 7 example data) }); console.log(objectz);
Comments
Post a Comment