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 to add array value into my existing obj, I got {1,2,10} where 3 to 9 is got override, where is my mistake?
Aside from syntax errors (copy/paste error?), your code is iterating through objArr
and overwriting a property literally called "key"
on objectz
(ie objectz.key
). You are not using the function parameter iterator called key
. If you wanted to use the function parameter called key to update objectz
then you probably want to use objectz[key]
.
It is hard to guess what localStorage.getItem('myItem')
returns. Assuming objArr = [{c: 3},{d: 4},{e: 5},{f: 6},{g: 7},{h: 8},{i: 9},{j: 10}]
, here is a corrected version of your 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 a property called 'key' for each element of objArr
//});
$.each(objArr, function(key,obj){
objectz[key] = obj;//key will be the zero based array index (i.e. 0 to 7 for the example data)
});
console.log(objectz);
var objx = {};
objx.a = 1;
objx.b = 2
var objArr = JSON.parse(localStorage.getItem('myItem'));
$.each(objArr, function(key,obj){
objx[key] = obj;
}
console.log(objx);
object is a reserve word i believe if i am not mistaken
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.