I have an array with Questions. Each question has options to pick from and the correct answer. I am trying to add true/false if the option is correct. How should I best do this? I tried .map()
and .forEach
but I don’t know how to access correct_answer
and use that to add the true/false
values under options.
const data = [
{
"question": "What is the approximate value of mathematical constant e?",
"options": [
{
"option": "1.41",
},
{
"option": "1.62",
},
{
"option": "2.72",
},
{
"option": "3.14",
}
],
"correct_answer": "2.72"
},
{
"question": "What is the name of the main character of the anime "One-Punch Man"?",
"options": [
{
"option": "Genos",
},
{
"option": "King",
},
{
"option": "Saitama",
},
{
"option": "Sonic",
}
],
"correct_answer": "Saitama"
}
]
Desired result
const data = [
{
"question": "What is the approximate value of mathematical constant e?",
"options": [
{
"option": "1.41",
"correct_answer": false,
},
{
"option": "1.62",
"correct_answer": false,
},
{
"option": "2.72",
"correct_answer": true,
},
{
"option": "3.14",
"correct_answer": false,
}
],
"correct_answer": "2.72"
},
{
"question": "What is the name of the main character of the anime "One-Punch Man"?",
"options": [
{
"option": "Genos",
"correct_answer": false,
},
{
"option": "King",
"correct_answer": false,
},
{
"option": "Saitama",
"correct_answer": true,
},
{
"option": "Sonic",
"correct_answer": false,
}
],
"correct_answer": "Saitama"
}
]
2
Answers
You can use
Array.map
to update the values and thespread
operator to populate the objects.