Having a JSON in this format:
[{ 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 } ]
how can I combine the objects by name
, country
, and countryID
in Javascript to get the following JSON output?
[{ country: "Y", countryID: "01", valueA: 25, valueB: 45 }, { country: "X", countryID: "02", valueA: 15, valueB: 35 } ]
Advertisement
Answer
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);