2

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
  }
]
1
  • 2
    Please edit your question to show what you've tried, where you're stuck, output issues, errors, etc. Commented Nov 4, 2020 at 17:02

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.