adding an element to JSON Array JavaScript -
i have following array in source code:
var employees = [ { "question":"question 1", "answer":"answer 1" }, { "question":"question 1", "answer":"another answer 1" }, { "question":"question 2", "answer":"answer 2" } ];
i need create function can group answers related same question , put info in json object
{ "question":"question 1", "answer" : '[{"answer 1","another answer 1"}]' }, { "question":"question 2", "answer" : '[{"answer2"}]' }
as said in comments, wrote answers strings not array of strings.
what may want acheive :
var employees = [ { "question":"question 1", "answers": ["answer 1"] }, { "question":"question 2", "answers": ["answer 2", "some other answer", "... etc"] } ]; // add answers question 1 employees[0].answers.push('a new anwser 1'); // add anwers question 2 employees[1].answers.push('a new answer 2'); // ... , on
that's how see if want clean way add answers , have answers related questions directly
now function :
var employees = [ { "question":"question 1", "answer":"answer 1" }, { "question":"question 1", "answer":"another answer 1" }, { "question":"question 2", "answer":"answer 2" } ]; function groupanswerstoquestions(employees){ var questions = [], result = []; // set questions same string same key for(var k in employees){ // set question array if not set yet var q = employees[k].question; if( ! questions[q]) questions[q] = []; // add answer array questions[q].push(employees[k].answer); } // re render new array wanted structure for(var k2 in questions){ result.push({ question: k2, answers: questions[k2] }); } return result; } alert( json.stringify( groupanswerstoquestions(employees), null, 2) );
Comments
Post a Comment