【问题标题】:Group values by a specific key in a nested array按嵌套数组中的特定键对值进行分组
【发布时间】:2022-06-17 21:30:31
【问题描述】:

在嵌套数组/对象中通过name 键对项目进行分组的最有效方法是什么?

这里的主数组看起来像这样:

let arr = [
  {
    id: 123,
    compensatedItems: [
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Another random item',
        id: '24122',
        reason: 'missing_items',
      },
      {
        name: 'Another random item',
        id: '24122',
        reason: 'missing_items',
      },
    ],
  },
  {
    id: 341,
    compensatedItems: [
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Random item 1',
        id: '123512',
        reason: 'missing_items',
      },
      {
        name: 'Another random item',
        id: '24122',
        reason: 'missing_items',
      },
    ],
  },
];

您有一个包含多个对象的主数组,每个对象都有一个 compensatedItems 数组,其中包含其他对象。

我想将 compensatedItems 按名称分组,以便最终结果看起来像

let res = [
  {
    name: 'Random item 1',
    id: '123512',
    reason: 'missing_items',
    count: 5,
  },
  {
    name: 'Another random item',
    id: '24122',
    reason: 'missing_items',
    count: 3,
  },
];

这是没有任何意义的日子,并且很难在不循环 1000 次的情况下提出有效的解决方案。 ??????????‍♂️

谢谢!

【问题讨论】:

  • 为什么不使用两个嵌套循环呢?出了什么问题?

标签: javascript arrays data-structures


猜你喜欢
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-14
相关资源
最近更新 更多