[英]underscore.js groupBy sub-array
I have some data 我有一些数据
var data = [
{type: "A", role:[1,2]},
{type: "B", role:[2]},
{type: "C", role:[2,3]},
{type: "D", role:[3]}
];
I'm trying to sortBy 'role' using underscore.js 我正在尝试使用underscore.js对角色进行排序
var groups = _(data).groupBy(function(el){
return el.role
}
);
Is there a easy way to get reapeated data like this 是否有一种简单的方法来获取这样的收尾数据
1: {
{type:"A" ...}
},
2: {
{type:"A" ...},
{type:"B" ...},
... etc
not like this http://jsbin.com/IzEwUkim/2/edit 不喜欢这个http://jsbin.com/IzEwUkim/2/edit
You can, as usual, do it by hand with _.reduce
, something like this: 您可以像往常一样使用
_.reduce
手动完成_.reduce
,如下所示:
var groups = _(data).reduce(function(memo, o) {
_(o.role).each(function(i) {
memo[i] = memo[i] || [ ];
memo[i].push(o);
});
return memo;
}, { });
Demo: http://jsfiddle.net/ambiguous/HDE3c/ 演示: http : //jsfiddle.net/ambiguous/HDE3c/
You could use a plain for
loop instead of _.each
to iterate over the roles of course. 当然,您可以使用普通的
for
循环而不是_.each
来迭代角色。
_.groupBy
isn't going to work here as the function/key is always a single value so I think you're stuck unwrapping the role
arrays by hand. _.groupBy
在这里不起作用,因为函数/键始终是单个值,所以我认为您一直无法手动展开role
数组。
I know you asked for underscore, but here's native js: 我知道您要求下划线,但这是本地js:
var map = {};
data.forEach(function(obj){
obj.role.forEach(function(roleVal){
(map[roleVal] = map[roleVal] || []).push(obj);
});
});
console.log(map);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.