使用 javascript 在 json 中合并对象

Combine objects in a json using javascript

具有以下格式的 JSON:

[{
    name: "A",
    country: "X",
    countryID: "02",
    value: 15
  },
  {
    name: "A",
    country: "Y",
    countryID: "01",
    value: 25
  },
  {
    name: "B",
    country: "X",
    countryID: "02",
    value: 35
  },
  {
    name: "B",
    country: "Y",
    countryID: "01",
    value: 45
  }
]

如何在 Javascript 中通过 namecountrycountryID 组合对象以获得以下 JSON 输出?

[{
    country: "Y",
    countryID: "01",
    valueA: 25,
    valueB: 45
  },
  {
    country: "X",
    countryID: "02",
    valueA: 15,
    valueB: 35
  }
]

使用 Array.prototype.reduce,您可以按 countrycountryID key-value 对对数组项进行分组,并将结果存储到生成的键的对象值中,如下所示。

const input = [{
    name: "A",
    country: "X",
    countryID: "02",
    value: 15
  },
  {
    name: "A",
    country: "Y",
    countryID: "01",
    value: 25
  },
  {
    name: "B",
    country: "X",
    countryID: "02",
    value: 35
  },
  {
    name: "B",
    country: "Y",
    countryID: "01",
    value: 45
  }
];

const groupBy = input.reduce((acc, cur) => {
  const key = `${cur.country}_${cur.countryID}`;
  acc[key] ? acc[key][`value${cur.name}`] = cur.value : acc[key] = {
    country: cur.country,
    countryID: cur.countryID,
    ['value' + cur.name]: cur.value
  };
  return acc;
}, {});

const output = Object.values(groupBy);
console.log(output);