0

Here is my problem:

I have a JSON structure as below

[{
    "groupid": 29,
    "percentage": 14
}, {
    "groupid": 29,
    "percentage": 22
}, {
    "groupid": 59,
    "percentage": 66,
}]

and i need to convert that into as below using Javascript.

{
    "29": [14, 22],
    "59": [66]
}
1
  • 3
    Can you please show what you've been trying? Commented Oct 31, 2018 at 2:59

1 Answer 1

4

reduce the input into an object. On each iteration, create an array at the groupid key in the accumulator object if it doesn't exist yet, and then push to the array:

const input = [{
    "groupid": 29,
    "percentage": 14
}, {
    "groupid": 29,
    "percentage": 22
}, {
    "groupid": 59,
    "percentage": 66,
}];
const output = input.reduce((a, { groupid, percentage }) => {
  if (!a[groupid]) a[groupid] = [];
  a[groupid].push(percentage);
  return a;
}, {});
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.