将数组对象添加到对象中

时间:2015-07-30 09:16:18

标签: javascript jquery json

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);

我想将数组值添加到现有的obj中,我得到{1,2,10},其中3到9被覆盖,我的错误在哪里?

2 个答案:

答案 0 :(得分:0)

除了语法错误(复制/粘贴错误?)之外,您的代码正在迭代objArr并覆盖"key"上名为objectz的属性(即objectz.key) 。您没有使用名为key的函数参数迭代器。如果您想使用名为key的函数参数来更新objectz,那么您可能希望使用objectz[key]

很难猜出localStorage.getItem('myItem')返回的是什么。假设objArr = [{c: 3},{d: 4},{e: 5},{f: 6},{g: 7},{h: 8},{i: 9},{j: 10}],这是您的代码的更正版本:

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);

答案 1 :(得分:-1)

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);

对象是一个保留词我相信如果我没有错的