Jon Donnell Jon Donnell - 4 years ago 117
Javascript Question

How do I dynamically add objects to an object's property?

I am building a questionnaire and the questions can have multiple answers and I need to build an array of the question and answers such as:

{
question: 'question',
answer: {id: 1, answers: 'answer 1'},
{id: 2, answer: 'answer 2'}
}


I need to show a summary of the questions and the answers that the user chose.

For example: Question: Which of these states have you lived in?
answers: Alabama, Alaska, New Jersey, Rhode Island.

The resulting object could be:

{
question: 'Which of these states have you lived in?',
answer: {id: 1, answer: 'Alaska'},
{id: 3, answer: 'Rhode Island'}
}


How do I go about dynamically adding the answers while only having the question show up once?

I tried:

var questionAnswerObject = [];
angular.forEach(answersObject, function(value, key){
questionAnswerObject.push({
question: question.question,
answer: value.answer
});
});


But of course it shows the question twice.

Answer Source

Your missing something very important: you need answers to be an array (or an object), containing all the answers. You can't assign multiple objects to a value the way you are trying to do - they need to be wrapped somehow.

So, for example, your answer object might look like this instead:

var answerObject = {
  question: 'My Question',
  answers: [
    {id: 1, answer: 'first answer'},
    {id: 2, answer: 'second answer'}
  ]
}

Or, you could just make answers a map of the question ids like this:

var answerObject = {
  question: 'My Question',
  answers: {
    1: 'first answer',
    2: 'second answer'
  }
}

To add an answer in the first example, simply do:

answerObject.answers.push( {id: 3, answer: 'new answer'} );

To add an answer in the second example, simply do:

answerObject.answers[3] = 'new answer';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download