简体   繁体   中英

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

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

You can, as usual, do it by hand with _.reduce , something like this:

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/

You could use a plain for loop instead of _.each to iterate over the roles of course.

_.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.

I know you asked for underscore, but here's native js:

var map = {};
data.forEach(function(obj){
  obj.role.forEach(function(roleVal){
    (map[roleVal] = map[roleVal] || []).push(obj);
  });
});
console.log(map);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM