daveycroqet daveycroqet - 4 months ago 19
JSON Question

Weighting object values and determining a winner

I am attempting to weight the answers of a multiple choice quiz and calculate the winner. In the below JSON, selecting the answer

A
twice will get you 4 "points".

How do I iterate through all the answers, and tally them up with their respective weightings taken into account? I understand the logic behind determining a winner, but simply tallying the values is tripping me up.

The JSON structure is as follows:

{
"questions": [
{
"answers": [
{
"value": "A",
"weight": "1"
},
{
"value": "B",
"weight": "2"
},
{
"value": "C",
"weight": "3"
},
{
"value": "D",
"weight": "4"
}
]
},
{
"answers": [
{
"value": "B",
"weight": "4"
},
{
"value": "D",
"weight": "1"
},
{
"value": "A",
"weight": "3"
},
{
"value": "C",
"weight": "2"
}
]
}
]
}

Answer

You can get the answers and the sum of their corresponding weights using the below function. Where data is the object in question. Check this Fiddle.

var out = {};
data.questions.forEach(function(ans) {
    ans.answers.forEach(function(indv) {
        out[indv.value] = (out[indv.value] || 0) + parseInt(indv.weight, 10);
    });
});
console.log(out);