我有以下数据数组:
var ans =
[
{"text":"x","response":false},
{"text":"y","response":false},
{"text":"z","response":true}
];
var correct = "010"; // I need to add this to the array ans
任何人都可以建议我如何使用正确变量中的数据添加到数组中以便:
var ans =
[
{"text":"x","response":false,"correct":false},
{"text":"y","response":false,"correct":true},
{"text":"z","response":true,"correct":false}
];
答案 0 :(得分:2)
for(var i=0; i< ans.length; i++) {
ans[i].correct = correct.charAt(i) == "1";
}
答案 1 :(得分:2)
for (var i = 0; i < correct.length; i++) {
ans[i]["correct"] = correct[i] === "1";
}
答案 2 :(得分:1)
你也是这样做的(使用for-in循环)。
参考:For-each over an array in JavaScript?
for(key in ans){
ans[key].correct = correct.charAt(key) == "1";
}
答案 3 :(得分:0)
var ans =
[
{"text":"x","response":false},
{"text":"y","response":false},
{"text":"z","response":true}
];
var correct = "010";
var sep = correct.split("");
var arr = [];
for (var i = 0; i < sep.length; i++) {
if (sep[i] == 0) {
arr.push("false");
} else {
arr.push("true");
}
}
var len = ans.length;
for (var i = 0; i < len; i++) {
ans[i].correct = arr[i];
}