2014-10-03 78 views
1

我与我的分组类别阵列集合在这样的例子挣扎:Underscore.js - GROUPBY嵌套阵列

var programs = [ 
    { 
    name: 'a', 
    categories: ['cat1', 'cat2'] 
    }, 
    { 
    name: 'b', 
    categories: ['cat2'] 
    }, 
    { 
    name: 'c', 
    categories: ['cat1', 'cat3'] 
    } 
]; 

如果你这样做:

_.groupBy(programs, function(item){ return item.categories; }); 

它返回:

{ 
    'cat1, cat2': Array[1], 
    'cat1, cat3': Array[1], 
    'cat2': Array[1] 
} 

回答

3

经过互联网搜索后,我试了我自己的,并与Underscore.js

最后我得到了这对我的作品的解决方案:

var group = _.groupBy(_.flatten(_.pluck(programs, 'categories')), function(item){ 
    return item; 
}); 

这将返回:

{ 
    'cat1': Array[2], 
    'cat2': Array[2], 
    'cat3': Array[1] 
} 

http://jsfiddle.net/pypurjf3/2/

我希望这将帮助一些人用同样的问题所困扰。

+0

尼斯时间:-)正是我一直在寻找(从字面上看,我也有多个类别)。 – Kallex 2014-10-06 17:09:51

+0

显然这并没有解决我的情况,但无论如何,给了洞察力和想法追求前进。 – Kallex 2014-10-06 18:17:33

+0

你有我的小提琴吗?也许我可以帮助你。 – BastianW 2014-10-06 23:01:15

0

我有类似的问题,但想要多做一些分组出来。这是我结束了:

function groupByNested(theList, whichValue) { 
 
    // Extract unique values, sort, map as objects 
 
    var groups = _.chain(theList).pluck(theList, whichValue).flatten().uniq().reject(function(v) { return v==''; }).sort().map(function(g) { return { group: g, items: [] }; }).value(); 
 
    
 
    // Iterate through the array and add applicable items into the unique values list 
 
    _.each(_ls.plants, function(p) { 
 
    _.each(p[whichValue], function(v) { 
 
     theGroup = _.find(groups, function(g) { return g.group == v; }); 
 
     theGroup.items.push(p); 
 
    }); 
 
    }); 
 
    return groups; 
 
}