【问题标题】:Combine object values within an array using key value [duplicate]使用键值组合数组中的对象值[重复]
【发布时间】:2019-09-21 00:19:32
【问题描述】:

我正在尝试按 id 对跟随数组进行分组。

我尝试过使用 lodash,但我的结果也是重复 id 即"id":[6,6,6,6]

这是我现有的数组;

[
  {
    "nestedGroups": 64,
    "id": 6
  },
  {
    "nestedGroups": 27,
    "id": 6
  },
  {
    "nestedGroups": 24,
    "id": 6
  },
  {
    "nestedGroups": 69,
    "id": 6
  }
]

我的预期结果是使用 id 作为键将nestedGroups 组合成一个数组。

[
  {
    "nestedGroups": [64,27,24,69],
    "id": 6
  }
]

【问题讨论】:

  • 你能展示一下你的尝试吗?

标签: javascript arrays duplicates javascript-objects


【解决方案1】:

您可以使用reduce()find()

let arr = [ { "nestedGroups": 64, "id": 6 }, { "nestedGroups": 27, "id": 6 }, { "nestedGroups": 24, "id": 6 }, { "nestedGroups": 69, "id": 6 } ]

const res = arr.reduce((ac,a) => {
  let temp = ac.find(x => x.id === a.id);
  if(!temp) ac.push({...a,nestedGroups:[a.nestedGroups]})
  else temp.nestedGroups.push(a.nestedGroups)
  return ac;
},[])
console.log(res)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多