简体   繁体   中英

underscore groupby return array instead of object

I'm trying to create an array of entities grouped by location using underscore.

I have an array of pairs, which looks like this currently { location: Location, data: T}[] I would like to transform it to group by the location look like this { location: Location, data: T[]}>[]

My first instinct was to use _.GroupBy

const entitiesMap = entities.map(e => ({ location: this.options.locationResolver(e), data: e}));
this.locationEntitiesMap = _.groupBy(entitiesMap, entityPair => entityPair.location);

However when I do this this returns an object with the location as the Key. How can I return a grouped array instead?

I would use a reduce

 const places = [ { location: {id: 'USA'}, data:{ eventName:'tech week' }}, { location: {id: 'GER'}, data:{ eventName:'cheese wheeling' }}, { location: {id: 'USA'}, data:{ eventName:'mecha fights' }}, { location: {id: 'AUS'}, data:{ eventName:'kangaroo fight' }} ]; const group = (array, prop) => array.reduce((g, item) => { const propVal = item[prop]; const identifier = propVal.id; const entry = g[identifier]; const data = item.data; if (entry) { entry.data.push(data); } else { g[identifier] = {location: propVal, data: [data]}; } return g; }, {}); const groups = group(places, 'location'); console.log(group(Object.keys(groups).map((key) => groups[key]), 'location'));

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