当给定另一个包含要更新的字段状态的数组时,如何更新数组的一个字段?

时间:2013-09-18 10:45:52

标签: javascript

我有一个包含一系列答案的变量,如下所示:

var answers = [
   {"answerId":5,"text":"<p>xx</p>","correct":null,"response":true},
   {"answerId":6,"text":"<p>yy</p>","correct":null,"response":false},
   {"answerId":7,"text":"<p>zz</p>","correct":null,"response":false},
   {"answerId":8,"text":"<p>aa</p>","correct":null,"response":false},
   {"answerId":9,"text":"<p>bb</p>","correct":null,"response":false},
   {"answerId":21,"text":"<p>cc</p>","correct":null,"response":false}];

和另一个包含响应数组的变量:

var reply = [
   {"answerId":5,"correct":true},
   {"answerId":6,"correct":false},
   {"answerId":7,"correct":false},
   {"answerId":8,"correct":false},
   {"answerId":9,"correct":false},
   {"answerId":21,"correct":false}];

如何使用每个answerId的正确答案更新答案变量?那么null被替换了吗?

1 个答案:

答案 0 :(得分:1)

如果我们知道索引和答案是相同的(否则我们可以对它们进行排序)。一个简单的for循环可以处理这个问题。

for(var i=0;i<answers.length;i++){
    answers[i].correct = reply[i].correct;
}

Fiddle