下划线 groupby return 数组而不是对象
underscore groupby return array instead of object
我正在尝试使用下划线创建按位置分组的实体数组。
我有一个数组对,目前看起来像这样 { 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);
然而,当我这样做时,returns 是一个以位置为键的对象。
我怎样才能 return 分组数组呢?
我会使用 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'));
我正在尝试使用下划线创建按位置分组的实体数组。
我有一个数组对,目前看起来像这样 { 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);
然而,当我这样做时,returns 是一个以位置为键的对象。 我怎样才能 return 分组数组呢?
我会使用 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'));