【发布时间】:2018-10-28 09:35:25
【问题描述】:
所以我有一组数据,比如说......
{'action': 'tweet', 'user': 'loser', 'message': 'fooboo'}
{'action': 'follow', 'user': 'loser', 'message': null }
{'action': 'tweet', 'user': 'loser', 'message': 'hello'}
{'action': 'retweet', 'user': 'loser', 'message': null}
{'action': 'tweet', 'user': 'michael', 'message': 'CIA is watching'}
{'action': 'tweet', 'user': 'michael', 'message': 'HEHEHEHE'}
{'action': 'follow', 'user': 'michael', 'message': null }
我正在尝试使用 reduce 遍历它并返回一个用户列表,其中包含他们所有操作的计数,例如
{ loser:
{
tweets: 2
retweets: 1
follows: 1
}
}, michael:
{
tweets: 2
retweets: 0
follows: 1
}
}
这是我的代码...
let userCount = tweets.reduce(function(users, line, idx) {
users[line['users']] = users[line['user']] || [];
let action = line['action];
users[line.user].push({
action: users[line.user].action + 1 || 0
})
return users
}, {users: []});
我的代码没有成功计算或将动作的名称作为键注入对象。这就是我的输出数据的样子。
{ michael: [ { action: 1 } ],
loser: [ { action: 1 }, { action: 1 }, { action: 1 } ],
}
【问题讨论】:
-
您是要我们为您编写代码吗?您尝试了哪些方法,哪些方法不起作用?
-
用我拥有的当前代码编辑。对不起。我希望有一种更简单的方法来复制和粘贴代码,而不必每次缩进 8 个空格。
-
你还没说什么不行?
-
我只是对如何以这种方式成功地使用 reduce 操作对象感到困惑。每个在线资源都有一个非常基本的示例,例如 [2, 4, 4, 2, 1, 4, 5] 并返回每个数字的计数。我的稍微先进一点。我找不到类似格式的好例子。
标签: javascript arrays node.js object reduce