javascript - 根据数组类型键对对象数组进行分组

标签 javascript arrays ecmascript-6

输入如下:

[
  {
    gameId: id_0,
    groups: [1]
  },
  {
    gameId: id_1,
    groups: [2]
  },
  {
    gameId: id_2,
    groups: [1, 2]
  },
  {
    gameId: id_3,
    groups: [3]
  }
]

我希望我的 reduce 产生如下对象数组:

[
  {
    group: 1,
    data: [
      id_0, id_2 // gameId
    ]
  },
  {
    group: 2,
    data: [
      id_1, id_2
    ]
  },
  {
    group: 3,
    data: [
      id_3
    ]
  }
]

我能够通过使用数组索引部分解决这个问题。 我目前的代码是:

groupByArr = parameter => data => data.reduce((acc, curr) => {
  curr[parameter].forEach(key => {
    if (acc[key]) {
      acc[key].push(curr)
    } else {
      acc[key] = [curr]
    }
  })
  return acc
}, [])

它生成一个数组数组,其中主数组索引是组 ID:

[
  empty,
  1: [
    id_0, id_2
  ],
  2: [
    id_1, id_2
  ],
  3: [
    id_3
  ]
]

最佳答案

您可以使用 Array.prototype.reduce()结合 Array.prototype.forEach()Array.prototype.push()返回一个对象并最终使用 Object.values() 获取值

代码:

const data = [{gameId: 'id_0',groups: [1]},{gameId: 'id_1',groups: [2]},{gameId: 'id_2',groups: [1, 2]},{gameId: 'id_3',groups: [3]}]
const result = Object.values(data.reduce((acc, {gameId, groups}) => {
  groups.forEach(group => {
    acc[group] = acc[group] || { group, data: [] }
    acc[group].data.push(gameId)
  })
  return acc
}, {}))

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 根据数组类型键对对象数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58004096/

相关文章:

javascript - Google Maps API 不显示地点

javascript - 如何让一个函数仅在另一个函数完全启动后才启动?

javascript - 从映射数组返回 React 组件

javascript - 对象传播过滤键

java - 如何在递归中做一次性的事情?

angularjs - 我可以在 AngulrJS 1.3.0 项目中使用 angular/di.js 吗?

javascript - 类似 JavaScript 中的 include() 函数

javascript - jquery 导航在幻灯片上向上滚动,不起作用

javascript - 通过 ajax 将命名数组发送到 PHP

java - kotlin:注释中数组的一些问题