如何动态地将对象添加到对象的属性?

时间:2015-12-31 20:24:26

标签: javascript angularjs javascript-objects

我正在构建问卷,问题可以有多个答案,我需要建立一个问题和答案的数组,例如:

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

我需要显示用户选择的问题和答案的摘要。

例如:问题:你住在哪些州? 答案:阿拉巴马州,阿拉斯加州,新泽西州,罗德岛州。

结果对象可能是:

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

如果只显示一次问题,我该如何动态添加答案?

我试过了:

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

但当然它会两次显示问题。

3 个答案:

答案 0 :(得分:1)

你遗失的东西非常重要:你需要answers成为一个数组(或一个对象),包含所有的答案。你不能按照你想要的方式将多个对象分配给一个值 - 它们需要以某种方式包装。

因此,例如,您的答案对象可能会这样:

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

或者,您可以像answers一样制作问题ID的地图:

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

要在第一个示例中添加答案,只需执行以下操作:

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

要在第二个示例中添加答案,只需执行以下操作:

answerObject.answers[3] = 'new answer';

答案 1 :(得分:0)

我认为你的意思是你的最终目标就像这个问题和一系列答案

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

所以如果你有循环投掷问题并添加答案如下

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"});

答案 2 :(得分:0)

实现这一目标的最佳方法是:

    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 ;