Ali-Alrabi Ali-Alrabi - 4 months ago 17
Javascript Question

Convert json format to another json format by AngularJS

I'm trying to implement a questionnaire with angularjs,So I have the following response array ,I need to convert this object array to json format like the following output, So How can I convert object array to json format?

var response=[{"questiongroup":1,"question":1,"response":"response1"},
{"questiongroup":1,"question":2,"response":"response2"},
{"questiongroup":1,"question":3,"response":"response3"},
{"questiongroup":1,"question":4,"response":"response4"},
{"questiongroup":1,"question":5,"response":"response5"},
{"questiongroup":2,"question":6,"response":"response6"},
{"questiongroup":2,"question":7,"response":"response7"},
{"questiongroup":2,"question":8,"response":"response8"},
{"questiongroup":2,"question":9,"response":"response9"},
{"questiongroup":2,"question":10,"response":"response10"}];


desired output

{"questiongroups": [
{
"questiongroup": 1,
"question": [
{
"question": 1,
"response":"response1"
},
{
"question": 2,
"response":"response2"
},
{
"question": 3,
"response":"response3"
},
{
"question": 4,
"response":"response4"
},
{
"question": 5,
"response":"response5"
}]
},
{
"questiongroup": 2,
"question": [
{
"question": 6,
"response":"response6"
},
{
"question": 7,
"response":"response7"
},
{
"question": 8,
"response":"response8"
},
{
"question": 9,
"response":"response9"
},
{
"question": 10,
"response":"response10"
}]
}
]
}

Answer

The fastest solution that came to me.

Reduces the response to a object with the questiongroup being the ids of the arrays. Then, to return as you want, mapped the keys to generate the array and created the object with the questiongroups value.

var response=[{"questiongroup":1,"question":1,"response":"response1"},
                     {"questiongroup":1,"question":2,"response":"response2"},
                     {"questiongroup":1,"question":3,"response":"response3"},
                     {"questiongroup":1,"question":4,"response":"response4"},
                     {"questiongroup":1,"question":5,"response":"response5"},
                     {"questiongroup":2,"question":6,"response":"response6"},
                     {"questiongroup":2,"question":7,"response":"response7"},
                     {"questiongroup":2,"question":8,"response":"response8"},
                     {"questiongroup":2,"question":9,"response":"response9"},
                     {"questiongroup":2,"question":10,"response":"response10"}];

var questiongroups = response.reduce(function(groups, question){
  var group = groups[question.questiongroup] || [];
  group.push({
    question: question.question,
    response: question.response
  });

  groups[question.questiongroup] = group;
  
  return groups;
}, {});

questiongroups = Object.keys(questiongroups).map(function (key) {return {questiongroup: key, question: questiongroups[key]}});

var object = {
  questiongroups: questiongroups
};

console.log(object);