简体   繁体   中英

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.

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';

What I think of you mean your final object to be like this question and array of answers

var arrayObjQuestions = [{
    question: 'question', 
    answer: [{id: 1, answers: 'answer 1'}, 
             {id: 2, answer: 'answer 2'}]
},...];

so if loop throw questions you have and add answer as follow

arrayObjQuestions[0].answer.push({id:1, answer: "answer 1"});
arrayObjQuestions[0].answer.push({id:2, answer: "answer 2"});
arrayObjQuestions[0].answer.push({id:3, answer: "answer 3"});

The best way to achieve this, use:

    var questionAnswerObject = {};
    var answers = [];

    answers.push({id:1, answer: 'Alaska'});
    answers.push({id:3, answer: 'Rhode Island'});  

    questionAnswerObject["question"] = 'Which of these states have you lived in?';
    questionAnswerObject["answer"] = answers ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM