[英]How can I use data in a string to update a javascript object?
我有以下數據數組:
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}
];
for(var i=0; i< ans.length; i++) {
ans[i].correct = correct.charAt(i) == "1";
}
for (var i = 0; i < correct.length; i++) {
ans[i]["correct"] = correct[i] === "1";
}
您也可以這樣做(使用for-in循環)。
for(key in ans){
ans[key].correct = correct.charAt(key) == "1";
}
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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.