Lodash get repetition count with the object itself

时间:2015-10-30 21:42:45

标签: javascript underscore.js lodash

I have an array of objects like:

[  {
"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"
} ]

I want to get:

[  {
"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
} ]

I've used lodash a.k.a. underscore for this method but failed to process it.

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);
    });

The result should be in resComment.

EDIT: Updated array of objects.

2 个答案:

答案 0 :(得分:2)

I'd look into using _.reduce(), since that's what you're doing--reducing the given array into a (potentially) smaller array containing a different sort of object.

Using _.reduce(), you'd do something like this:

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;
}, []);

And here is a JSFiddle.

答案 1 :(得分:0)

You can get pretty close using countBy:

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

We could go further, using _.keys() to iterate through the counts object and transforming them into your final result set, but you can probably achieve that bit easily enough using _keys.