Lodash获取对象本身的重复计数

Lodash get repetition count with the object itself

本文关键字:获取 取对象 Lodash      更新时间:2023-09-26

我有一个对象数组,比如:

[  {
"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,也就是下划线,但没能处理它

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中。

EDIT:更新的对象数组。

我会研究使用_.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

使用countBy:可以非常接近

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

我们可以更进一步,使用_.keys()来遍历count对象,并将它们转换为最终结果集,但使用_keys可能可以很容易地实现这一点。