combine objects in a json using javascript

Using Array.prototype.reduce, you can group array items by country and countryID key-value pairs and store the result to the object values of that generated key as follows.

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);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top