Lodash 使用对象本身获取重复计数

Lodash get repetition count with the object itself

我有一组对象,例如:

[  {
"username": "user1",
"profile_picture": "TESTjpg",
"id": "123123",
"full_name": "User 1"
}, {
"username": "user2",
"profile_picture": "TESTjpg",
"id": "43679144425",
"full_name": "User 2"
}, {
"username": "user2",
"profile_picture": "TESTjpg",
"id": "43679144425",
"full_name": "User 2"
} ]

我想得到:

[  {
"username": "user1",
"profile_picture": "TESTjpg",
"id": "123123",
"full_name": "User 1",
"count": 1
}, {
"username": "user2",
"profile_picture": "TESTjpg",
"id": "43679144425",
"full_name": "User 2",
"count": 2
} ]

我用过 lodash a.k.a。此方法的下划线但未能处理它。

var uniqueComments =  _.chain(comments).uniq(function(item) { return item.from.id; }).value();
    var resComment = [];
    _.forEach(uniqueComments, function(unco) {
        unco.count = _.find(comments, function(comment) {
            return unco.id === comment.id
        }).length;

        resComment.push(unco);
    });

结果应该在resComment.

编辑:更新了对象数组。

你可以使用 countBy:

var counts = _.countBy(uniqueComments, 'name');

我们可以更进一步,使用 _.keys() 遍历计数对象并将它们转换为您的最终结果集,但您可能可以使用 _keys 轻松实现这一点。

我会考虑使用 _.reduce(),因为这就是您正在做的事情——将给定数组缩减为包含不同类型对象的(可能)更小的数组。

使用 _.reduce(),你会做这样的事情:

var resComment = _.reduce(comments, function(mem, next) {
    var username = next.username;
    var existingObj = _.find(mem, function(item) { return item.username === username; });
    existingObj ? existingObj.count++ : mem.push(_.extend(next, {count: 1}));
    return mem;
}, []);

这是一个 JSFiddle