我有以下要重组的数组
{
"feedId": 1,
"status": "read",
"count": 105
},
{
"feedId": 2,
"status": "read",
"count": 46
},
{
"feedId": 3,
"status": "read",
"count": 29
}
当我使用以下函数时,出现错误TypeError:无法设置未定义的属性“ read”。
var feeds = [];
statusCountGrouped.forEach(function(item) {
feeds[item.feedId][item.status] = item.count;
});
为什么不起作用?
答案 0 :(得分:0)
feeds [item.feedId] 未初始化。最简单的解决方案是根据需要在foreach中进行初始化。我有两种解决方案,如您所愿:
1 /
const statusCountGrouped = [
{
"feedId": 1,
"status": "read",
"count": 105
},
{
"feedId": 2,
"status": "read",
"count": 46
},
{
"feedId": 3,
"status": "read",
"count": 29
}
];
var feeds = [];
statusCountGrouped.forEach(function(item) {
if(feeds[item.feedId] === undefined) { feeds[item.feedId] = {}; }
feeds[item.feedId][item.status] = item.count;
});
console.log(feeds);
2 /
const statusCountGrouped = [
{
"feedId": 1,
"status": "read",
"count": 105
},
{
"feedId": 2,
"status": "read",
"count": 46
},
{
"feedId": 3,
"status": "read",
"count": 29
}
];
var feeds = [];
statusCountGrouped.forEach(function(item) {
feeds[item.feedId] = feeds[item.feedId] || {};
feeds[item.feedId][item.status] = item.count;
});
console.log(feeds);
答案 1 :(得分:0)
您收到错误消息,因为在分配之前未定义feeds[item.feedId]
。您应该先初始化它,然后再为feeds[item.feedId]
var feeds = [];
i.forEach(function(item) {
if (feeds[item.feedId] === undefined) feeds[item.feedId] = [];
feeds[item.feedId][item.status] = item.count;
});
希望这会有所帮助。