我正在尝试使用下划线创建按位置分组的实体数组。
我有一个成对的数组,目前看起来像这样{ location: Location, data: T}[]
,我想将其转换为按{ location: Location, data: T[]}>[]
这样的位置分组。
我的第一个直觉是使用_.GroupBy
const entitiesMap = entities.map(e => ({ location: this.options.locationResolver(e), data: e}));
this.locationEntitiesMap = _.groupBy(entitiesMap, entityPair => entityPair.location);
但是,当我执行此操作时,这将返回一个位置为Key的对象。 我该如何返回分组数组?
答案 0 :(得分:2)
我会使用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'));