javascript - 下划线 groupby 返回数组而不是对象

标签 javascript angular typescript underscore.js

我正在尝试使用下划线创建按位置分组的实体数组。

我有一个对的数组,目前看起来像这样 { 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/

相关文章:

javascript - PWA 无法在 iPhone/iPad 上以全屏模式打开

javascript - Angular Material 2 - 在单元测试的 md-checkbox 中触发更改事件

angular - 如何直接转到选项卡

javascript - JS, CSS 菜单栏切换

JavaScript : Why do i have to click twice in the table to execute the colorActiveLine function?

javascript - 带有对象的 Mongoose 模式

javascript - 尝试使用 *ngFor 循环显示数组

angular - Angular 万能锤的使用方法

typescript - 测试 Typescript 中的字符串文字类型

angular2-highcharts : update rendered chart data