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}
];
1
  • What are you trying to do? Commented Jul 24, 2014 at 5:07

4 Answers 4

2
for(var i=0; i< ans.length; i++) {
    ans[i].correct = correct.charAt(i) == "1";
}
Sign up to request clarification or add additional context in comments.

2 Comments

I see you are setting the value to "1" will this be the same as setting to true?
I'm not setting it to 1. I'm setting it to a result of (correct.charAt(i) == "1") comparison which is a boolean value: true or false
2
for (var i = 0; i < correct.length; i++) {
    ans[i]["correct"] = correct[i] === "1";
}

2 Comments

I see you are setting the value to "1" will this be the same as setting to true?
We are not setting the value to "1", we are setting the value to the result of comparison (correct[i] === "1"), which can be either true or false.
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";
}

1 Comment

I see you are setting the value to "1" will this be the same as setting to true?
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];
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.