Javascript 将元素推送到嵌套数组的问题
在以下代码中,我希望将新元素推送到数组中:Javascript 将元素推送到嵌套数组的问题,javascript,Javascript,在以下代码中,我希望将新元素推送到数组中: var temp = []; for(var i in resultDb){ temp.push({'ID':resultDb[i].ID}); temp.push({'Label':resultDb[i].Label}); temp.push({'User':[{'Name':resultDb[i].Name , 'ScreenName':resultDb[i].ScreenName}]}); temp.pu
var temp = [];
for(var i in resultDb){
temp.push({'ID':resultDb[i].ID});
temp.push({'Label':resultDb[i].Label});
temp.push({'User':[{'Name':resultDb[i].Name , 'ScreenName':resultDb[i].ScreenName}]});
temp.push({'TDate':resultDb[i].TDate});
}
for(var i in temp){
console.log(temp[i].User.ScreenName);
}
我得到的结果是无法读取未定义的属性“ScreenName”
。具体来说,问题在于用户
,但其他人都很好;它们可以打印出来
var temp = [];
//this loop pushes 4 elements in the array for each element in resultDb
for(var i in resultDb){
temp.push({'ID':resultDb[i].ID});
temp.push({'Label':resultDb[i].Label});
//why an array here?
temp.push({'User':[{'Name':resultDb[i].Name , 'ScreenName':resultDb[i].ScreenName}]});
temp.push({'TDate':resultDb[i].TDate});
}
//...therefore you have resultDb.length * 4 elements in temp.
//and only 1 every 4 elements has a User property
for(var i in temp){
console.log(temp[i].User.ScreenName);
}
您可能正试图这样做:
var temp = [];
for(var i in resultDb){
temp.push(Object.assign(
{'ID':resultDb[i].ID},
{'Label':resultDb[i].Label},
{'User':{'Name':resultDb[i].Name, 'ScreenName':resultDb[i].ScreenName}},
{'TDate':resultDb[i].TDate}
));
}
for(var i in temp){
console.log(temp[i].User.ScreenName);
}
这里有一个更好的方法:
var temp = resultDb.map(function (result) {
return Object.assign(
{'ID':result.ID},
{'Label':result.Label},
{'User':{'Name':result.Name, 'ScreenName':result.ScreenName}},
{'TDate':result.TDate}
);
})
for(var i in temp){
console.log(temp[i].User.ScreenName);
}
这不是数组的工作方式。您只是将新对象推送到阵列中。你推的所有对象都有不同的结构。因此,数组中的第一个条目没有以user属性开头 用户将导致未定义,因此:无法读取未定义的属性“ScreenName”
这里您要做的是获取{ID':result.ID}对象,并尝试从中读取user属性,但它只有一个ID属性 首先,temp应该是一个对象,而不是数组,{}而不是[] 对于“无法读取未定义的属性'ScreenName'” 有两种方法可以实现这一点,通常您会同时验证这两种方法
if( typeof resultDb[i] == 'undefined' )
return false;// index is not valid ?
var some_value = ( typeof resultDb[i].ScreenName == 'undefined' ? false : resultDb[i].ScreenName );
由于已将用户声明为数组
for(var i in temp){
console.log(temp[i].hasOwnProperty("User") ? temp[i].User[0].ScreenName : "not found");
}
User
是一个数组。请提供一份