javascript - 使用键值组合数组中的对象值

标签 javascript arrays duplicates javascript-objects

<分区>

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

我试过使用 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
  }
]

最佳答案

您可以使用 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)

关于javascript - 使用键值组合数组中的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953091/

相关文章:

javascript - Typescript/Angular 2 问题

c - 找到数组的最小元素并将其索引设置为 0

ios - Accelerate Framework 能否基于单独的索引数组聚合数组值?

redis - 多个 Logstash 实例导致行重复

duplicates - Apache Pulsar 中的重复数据删除如何工作?

javascript - react-redux 登录后重定向到其他页面

javascript - 根据内部数组值跳过 JSON 数据记录 - D3

streaming - 数据流中的近似重复检测

c# - 如何使用 .NET 的 WebBrowser 或 mshtml.HTMLDocument 动态生成 HTML 代码?

javascript - 使用 AJAX 和 PHP 将数据数组插入 SQL 中