【问题标题】:How to combine an array of object within same array and same keys using reduce如何使用 reduce 在同一数组和相同键中组合对象数组
【发布时间】:2022-12-05 14:11:55
【问题描述】:

我正在尝试使用 reduce 组合数组内的对象我的对象看起来像波纹管并且具有休闲结构。

[
    {
        "AREA": [
            "EMAC"
        ],
        "SUPER_REGION": [
            "South East Europe Region",
            "East Europe Region",
        ],
    },
    {
        "AREA": [
            "CCA"
        ],
        "SUPER_REGION": [
            "Taiwan",
            "China Hong Kong"
        ],
    }
    
]
预期产出

{
        "AREA": [
            "EMAC","CCA"
        ],
        "SUPER_REGION": [
            "South East Europe Region",
            "East Europe Region",
            "Taiwan",
            "China Hong Kong"
        ],
}

我当前使用 reduce 的代码:

let sum = finalval.reduce(function (accumulator, { AREA, SUPER_REGION }) {
    accumulator["AREA"] += AREA;
    return accumulator;
  }, {});

上面的代码通过将值组合成一个字符串来返回我的输出,但我希望将它们拆分并添加到单个对象中,如预期输出所示。我如何才能像使用 push 方法在数组上所做的那样实际将值推送到这些对象中?

【问题讨论】:

    标签: javascript object reduce


    【解决方案1】:

    您不仅需要将元素附加到AREA,还需要将元素附加到SUPER_REGION - 要将元素添加到数组,请使用.push,而不是+=。但这不会很笼统。一种更灵活的方法是通过首先映射一个输入对象来构造输出对象,将空数组作为值——然后对于每个输入对象,遍历每个子数组并推送到输出对象中的键。

    const input = [
        {
            "AREA": [
                "EMAC"
            ],
            "SUPER_REGION": [
                "South East Europe Region",
                "East Europe Region",
            ],
        },
        {
            "AREA": [
                "CCA"
            ],
            "SUPER_REGION": [
                "Taiwan",
                "China Hong Kong"
            ],
        }  
    ];
    
    const output = Object.fromEntries(
      Object.keys(input[0]).map(key => [key, []])
    );
    for (const obj of input) {
      for (const [key, subarr] of Object.entries(obj)) {
        output[key].push(...subarr);
      }
    }
    console.log(output);

    .reduce 在这里并不合适,假设您想保持输入不变。如果你使用.reduce,它看起来会是a bit confusing for no good reason

    const input = [{
        "AREA": [
          "EMAC"
        ],
        "SUPER_REGION": [
          "South East Europe Region",
          "East Europe Region",
        ],
      },
      {
        "AREA": [
          "CCA"
        ],
        "SUPER_REGION": [
          "Taiwan",
          "China Hong Kong"
        ],
      }
    ];
    
    const output = input.reduce((a, obj) => {
      for (const [key, subarr] of Object.entries(obj)) {
        a[key].push(...subarr);
      }
      return a;
    }, Object.fromEntries(Object.keys(input[0]).map(key => [key, []])));
    console.log(output);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2020-08-24
      • 1970-01-01
      • 2022-11-24
      • 2021-04-26
      • 1970-01-01
      相关资源
      最近更新 更多