我正在尝试使用下划线创建按位置分组的实体数组。
我有一个对的数组,目前看起来像这样 { location: Location, data: T}[]
我想将其转换为按位置分组,如下所示 { location:位置,数据:T[]}>[]
我的第一直觉是使用_.GroupBy
const entitiesMap = entities.map(e => ({ location: this.options.locationResolver(e), data: e}));
this.locationEntitiesMap = _.groupBy(entitiesMap, entityPair => entityPair.location);
但是,当我这样做时,会返回一个以位置为键的对象。 如何返回分组数组?
最佳答案
我会使用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'));
关于javascript - 下划线 groupby 返回数组而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59062399/