2017-08-02 23 views
0

我是javascript noobie,我开始使用库lodash,并遇到一些问题。有人能帮我吗? :/用lodash或ES5对对象进行分组

输入:

var a = [{group: 'A', title: 'test1', value: 'test2'}, 
     {group: 'A', title: 'test2', value: 'test3'}, 
     {group: 'B', title: 'test3', value: 'test4'}, 
     {group: 'B', title: 'test1', value: 'test2'},] 

输出:

var a = {A: [ 
     { title: 'test1', value: 'test2'}, 
     { title: 'test2', value: 'test3'} 
     ], 
     B: [ 
     { title: 'test1', value: 'test2'}, 
     { title: 'test2', value: 'test3'} 
     ],} 

回答

0

为组lodash文档通过是非常明确的,你可以找到它here

在你的情况下,它会是这个样子。

_.groupBy(a, 'group') 

你也可以自己做很容易地以及使用减少功能。这将是这个样子:

let groups = a.reduce((grouping, currentItem) => { 
    if (!grouping[currentItem.group]) { 
     grouping[currentItem.group] = [] 
    } 
    grouping[currentItem.group].push(currentItem); 
    return grouping; 
}, {}); 

工作示例可以发现here

在这两种情况下,结果都将是一个包含组作为属性名称的对象。

{ 
    "A": [{ 
    "group": "A", 
    "title": "test1", 
    "value": "test2" 
    }, { 
    "group": "A", 
    "title": "test2", 
    "value": "test3" 
    }], 
    "B": [{ 
    "group": "B", 
    "title": "test3", 
    "value": "test4" 
    }, { 
    "group": "B", 
    "title": "test1", 
    "value": "test2" 
    }] 
} 
0

可以与_.groupBy()然后组使用_.mapValues()对每个组通过将它们映射到使用_.omit()一个新的对象,以除去从对象group属性。

const a = [{group: 'A', title: 'test1', value: 'test2'}, 
 
     {group: 'A', title: 'test2', value: 'test3'}, 
 
     {group: 'B', title: 'test3', value: 'test4'}, 
 
     {group: 'B', title: 'test1', value: 'test2'} 
 
     ]; 
 
     
 
const result = _(a) 
 
    .groupBy('group') // group by the group prop 
 
    .mapValues((group) => group.map((o) => _.omit(o, 'group'))) // remove the group prop from each item 
 
    .value(); 
 
    
 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>