【问题标题】:Group array of objects by id typescript [duplicate]按id typescript对对象数组进行分组[重复]
【发布时间】:2021-10-05 02:21:59
【问题描述】:

我有这个对象数组

[
  { id: '1', foo: 'bar' },
  { id: '1', foo: 'foo' },
  { id: '4', bar: 'foo' }
]

我如何将它通过id 合并得到下面的结果?

想要的结果:

{
  '1': [
    { foo: 'bar' },
    { foo: 'foo' }
  ]
  '4': [
    { bar: 'foo' }
  ]
}

我尝试过 Object.entries,但这种方法不适用于我正在做的事情。

编辑

我阅读了this 问题的答案,首先他们都没有完全回答我的问题,其次他们也不是打字稿答案。

所有答案都是 key => val 而我需要 key => 该键的对象数组

【问题讨论】:

  • 你没有合并。你在分组。按 id 搜索 javascript 组
  • ... OP 是如何尝试的?这是一个经典的reduce 任务。
  • 那么那个问题的first answer 提供了一个完美返回您想要的结果的函数。只需使用groupBy(yourArray, 'id')
  • 请不要破坏您的帖子。通过在 Stack Exchange 网络上发布,您已根据 CC BY-SA 4.0 许可授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本,因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: javascript arrays typescript merge grouping


【解决方案1】:

您可以简单地使用Array.reduce 并相应地对它们进行分组。

const data = [
  { id: '1', foo: 'bar' },
  { id: '1', foo: 'foo' },
  { id: '4', bar: 'foo' }
]

const formatData = data => data.reduce((acc, {id, ...rest}) => {
  acc[id] ??= [];
  acc[id].push(rest);
  return acc;
}, {});

console.log(formatData(data));
.as-console-wrapper {
  max-height: 100% !important;
}

【讨论】:

【解决方案2】:

这是一个经典的reduce任务...

function groupItemRestById(collector, item) {
  const { id, ...rest } = item;
  const groupList = collector[id] || (collector[id] = []);

  groupList.push(rest);

  return collector;
}

console.log([

  { id: '1', foo: 'bar' },
  { id: '1', foo: 'foo' },
  { id: '4', bar: 'foo' },
  
].reduce(groupItemRestById, {}));
.as-console-wrapper { min-height: 100%!important; top: 0; }

【讨论】:

  • @henroper ...我不知道...但是在查看 TS-Spec 之后可能类似于 ...declare function groupItemRestById(collector: any, item: any): any; ...可能已经成功了。
猜你喜欢
  • 2017-04-27
  • 2022-01-14
  • 2022-12-16
  • 2020-02-29
  • 1970-01-01
  • 2014-11-28
  • 2022-06-22
  • 2020-06-06
  • 2012-06-23
相关资源
最近更新 更多