简体   繁体   中英

Is there any lodash function to achieve this?

I have an array

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}
]

I need output like this:

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

Here's a solution that first groups by id and then maps across the groupings to get the required collection:

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

It's pretty ugly, but then other answers are not pretty either

 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> 

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