0

I have the following array in my 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 to create a function that can group all the answers that are related to the same question and put the info in a JSON object

{ "Question":"question 1", "Answer" : '[{"answer 1","another answer 1"}]' }, { "Question":"question 2", "Answer" : '[{"answer2"}]' } 
4
  • You probably don't want it to look like that - don't you want the Answers to be a real array, not a string?CommentedAug 16, 2015 at 22:51
  • 2
    The first code is not JSON, it's an array initializer with object initializers. The second one seems to contain some invalid JSON.
    – Oriol
    CommentedAug 16, 2015 at 22:53
  • hello, my goal is to set to each question an array of answers of StringsCommentedAug 16, 2015 at 22:58
  • we understood your goal, but it wasn't properly written (the hash / json data), however you can check my function which does what you want, i put comments so your understand what i did @johnnymanolly
    – darkylmnx
    CommentedAug 16, 2015 at 23:59

7 Answers 7

4

This line has many problems

'[{"answer 1","another answer 1"}]' 

First, since it's inside quotes, it's a string, not an object. Second, you have an invalid object inside of an array.

If I understood you correctly, you're looking for something along the lines of

employee[x].answers = ['answer1','answer2']; 
    1

    As said in comments, you wrote your answers as strings not as an array of strings.

    What you may want to acheive is this :

    var employees = [ { "question":"question 1", "answers": ["answer 1"] }, { "question":"question 2", "answers": ["answer 2", "some other answer", "... etc"] } ]; // add answers to question 1 employees[0].answers.push('a new anwser 1'); // add anwers to question 2 employees[1].answers.push('a new answer 2'); // ... and so on 

    that's how i see it if you want a clean way to add answers and have your answers related to your questions directly

    Now the function for this would be :

    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 all questions with same string to the same key for(var k in employees){ // set the question to an array if not set yet var q = employees[k].Question; if( ! questions[q]) questions[q] = []; // add the answer to the array questions[q].push(employees[k].Answer); } // re render a new array with the wanted structure for(var k2 in questions){ result.push({ question: k2, answers: questions[k2] }); } return result; } alert( JSON.stringify( groupAnswersToQuestions(employees), null, 2) );

    1
    • this is very helpful, thnxCommentedAug 17, 2015 at 9:10
    1

    You can try this. call this function and pass the employees array to this and it will return your modified array

    function customJSON(employees){ var newEmp = [],tmp = 0; for(var i=0; i<employees.length; i++){ if(employees[i]){ if(newEmp.indexOf(employees[i].Question)>-1){ employees[newEmp.indexOf(employees[i].Question)].Answer.push(employees[i].Answer); employees.splice(i,1); --i; }else{ newEmp.push(employees[i].Question); tmp = employees[i].Answer; employees[i].Answer = [tmp]; } } } return employees; } 
      1

      var employees = [ { "Question":"question 1", "Answer":"answer 1" }, { "Question":"question 1", "Answer":"another answer 1" }, { "Question":"question 2", "Answer":"answer 2" }]; var employeesNewDataFormat = []; for(var i=0; i<employees.length; i++){ var hasEntry = false; var index = -1; for(var j=0; j<employeesNewDataFormat.length; j++) { if(employeesNewDataFormat[j].Question === employees[i].Question) { hasEntry = true; index = j; break; } } if(hasEntry) { employeesNewDataFormat[index].Answer.push(employees[i].Answer); } else { employeesNewDataFormat.push({"Question":employees[i].Question, "Answer":[employees[i].Answer]}); } } console.log(JSON.stringify(employeesNewDataFormat));

      0
        1

        You can use a map to keep track of the questions and add answers to the array attached to it:

        var employees = [{ "Question":"question 1", "Answer":"answer 1" }, { "Question":"question 1", "Answer":"another answer 1" }, { "Question":"question 2", "Answer":"answer 2" }]; var questions = {}; for (var i = 0; i < employees.length; i++) { if (questions[employees[i].Question] === undefined) { questions[employees[i].Question] = []; } questions[employees[i].Question].push(employees[i].Answer) } alert(JSON.stringify(questions, null, 2))

          1

          assuming that, like everyone is saying, you don't really mean what you wrote, but what we all understood, my advice for this case is using underscore, it has the perfect requirements for this case, your code would be:

          var result = _.chain(employees) .groupBy('Question') .map(function(value, key) { return { Question: key, Answer: _.pluck(value, 'Answer') } }) .value(); 
            1

            This is a bit crude and verbose but it does what I think you are asking for:

            var questions = {}; for (var i = employees.length - 1; i >= 0; i--) { var Question = ''; for (var property in employees[i]) { // console.log(property); var val = employees[i][property]; if (property == "Question") { Question = val; if (typeof questions[Question] == 'undefined') { questions[Question] = []; }; } if(property == 'Answer') { questions[Question].push(val); } }; }; var new_employees = []; for (var Question in questions) { var obj = { "Question": Question, "Answer": questions[Question] } new_employees.push(obj); }; console.log(new_employees); 

              Start asking to get answers

              Find the answer to your question by asking.

              Ask question

              Explore related questions

              See similar questions with these tags.