0

I have the following data array:

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

Can anyone suggest how I could use use the data in the correct variable to add to the array so as to make:

var ans = 
[
 {"text":"x","response":false,"correct":false},
 {"text":"y","response":false,"correct":true},
 {"text":"z","response":true,"correct":false}
];
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

4 Answers4

2
for(var i=0; i< ans.length; i++) {
    ans[i].correct = correct.charAt(i) == "1";
}
Anton L
  • 412
  • 4
  • 12
2
for (var i = 0; i < correct.length; i++) {
    ans[i]["correct"] = correct[i] === "1";
}
jw2013
  • 64
  • 1
  • 1
  • 3
1

You an also do it like this(using a for-in loop).

Reference: For-each over an array in JavaScript?

for(key in ans){
    ans[key].correct = correct.charAt(key) == "1";
}
Community
  • 1
  • 1
Kyle Emmanuel
  • 2,193
  • 1
  • 15
  • 22
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];
    }
Chakravarthy S M
  • 608
  • 6
  • 15