是否有任何lodash功能来实现这一目标?

时间:2017-04-28 14:51:45

标签: javascript lodash

我有一个数组

var a = [
   {id: 1, item: 3}, 
   {id: 1, item: 4}, 
   {id: 1, item: 5}, 
   {id: 2, item: 6}, 
   {id: 2, item: 7}, 
   {id: 3, item: 8}
]

我需要这样的输出:

[{id: 1, items: [3, 4, 5]}, {id: 2, items: [6,7]}, {id: 3, items: [8]}]

2 个答案:

答案 0 :(得分:1)

这是一个解决方案,首先按id进行分组,然后在分组中进行映射以获取所需的集合:

let result = _(a)
    .groupBy('id')
    .map( (group ,id) => ({id: id, items: _.map(group, 'item')}))
    .value()

答案 1 :(得分:0)

它非常丑陋,但其他答案也不是很好



var a = [
   {id: 1, item: 3}, 
   {id: 1, item: 4}, 
   {id: 1, item: 5}, 
   {id: 2, item: 6}, 
   {id: 2, item: 7}, 
   {id: 3, item: 8}
];

var ret = _.chain(a)
   
   .groupBy(elt => elt.id)
   .mapValues(elt => _.reduce(elt, (acc, sub) => acc.concat(sub.item),[]))
   .map((value, key) => ({id: key, items:value}))
   
   .value();
console.log(ret);

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;