-1

I need to process Array of Objects and format it as expected. How can I format array at this time?

Current Objects data

array = [
  {
    id: "1",
    answer: "d"
  },
  {
    id: "3",
    answer: "a"
  },
  {
    id: "3",
    answer: "b"
  },
  {
    id: "3",
    answer: "c"
  },
  {
    id: "4",
    answer: "b"
  },
  {
    id: "4",
    answer: "c"
  }
]

I want to format with javascript

formatArray = [
  {
    id: "1",
    answer: ["d"]
  },
  {
    id: "2",
    answer: []
  },
  {
    id: "3",
    answer: ["a","b","c"]
  }
  {
    id: "4",
    answer: ["b","c"]
  }
]

I need to process Array of Objects and format it as expected. How can I format array at this time?

jtk
  • 1
  • 2
  • note: that's an Array of Objects - it's not JSON (JSON is a **String**) - hint: use `Array#reduce` method – Jaromanda X Aug 02 '19 at 03:41
  • Welcome to StackOverflow! Have you tried anything so far? StackOverflow isn't a free code-writing service, and expects you to [try to solve your own problem first](http://meta.stackoverflow.com/questions/261592). Please update your question to show what you have already tried, showing the specific problem you are facing in a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve). For further information, please see [how to ask a good question](http://stackoverflow.com/help/how-to-ask), and take the [tour of the site](http://stackoverflow.com/tour) – Jaromanda X Aug 02 '19 at 03:42

1 Answers1

0
var data = array.reduce((acc, value) => { 
    acc[value.id] = acc[value.id] ? acc[value.id] : [];
    acc[value.id] ? acc[value.id].push(value.answer) : [value.answer];
    return acc;
}, {})

let result = Object.entries(data).map(d => ({ id: d[0], data: d[1] }) );
Shivam Mishra
  • 1,826
  • 1
  • 11
  • 16