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,也就是下划线,但没能处理它
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可能可以很容易地实现这一点。
相关文章:
- 从ajax请求中获取javascript对象
- 通过字符串获取JSON对象
- 如何在angular中获取json对象的名称
- 如何使用angular获取json对象的名称
- 获取一个对象´s属性的名称使用字符串
- 正在从嵌套值获取父对象
- 获取js对象键的值
- 获取原型对象的名称
- 如何从给定的代码中获取JSON对象
- 了解如何在数组中获取特定对象
- 获取整数对象属性名称的最小值和最大值
- 从Angular Scope中的Array中获取所有对象
- 在Javascript函数中获取Java对象属性
- 如何在JQUERY中从HTML文档中获取XML对象
- Backbone集合:如何从API中获取特定对象以放置在模型中
- 基于单个属性从数组中获取唯一对象
- 获取JSON对象中数组的长度
- 尝试获取每个对象的总和
- 正在尝试获取非对象php-DOM的属性
- 如何从HTML元素中获取Javascript对象