【问题标题】:Group all the values of common keys as an array in array of objects将公共键的所有值分组为对象数组中的数组
【发布时间】:2022-11-27 20:10:29
【问题描述】:

我有一个对象数组

const arr =   [
    
        {
            "id": 2,
            "key": "cc_edit"
        },
        {
            "id": 4,
            "key": "cc_upload"
        },
        {
            "id": 4,
            "key": "cc_download"
        },
        {
            "id": 1,
            "key": "cc_project"
        }]

我想要一个具有唯一键的对象作为新对象的键,其值作为数组。就像是:

{
   2 : ["cc_edit"],
   4 : ["cc_upload", "cc_download"],
   1 : ["cc_project"],
},

如何实现?

【问题讨论】:

标签: javascript arrays object ecmascript-6


【解决方案1】:

使用Array#reduce

const arr = [ { "id": 2, "key": "cc_edit" }, { "id": 4, "key": "cc_upload" }, { "id": 4, "key": "cc_download" }, { "id": 1, "key": "cc_project" } ];

const res = arr.reduce((acc, { id, key }) => ({
  ...acc,
  [id]: [...(acc[id] ?? []), key]
}), {});

console.log(res);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多