加权对象值并确定胜利者

时间:2016-07-14 00:40:50

标签: javascript json

我试图加权多项选择测验的答案并计算胜者。在下面的JSON中,选择答案A两次将获得4分“。

我如何迭代所有答案,并将他们各自的权重考虑在内?我理解确定胜利者背后的逻辑,但简单地计算价值观就是让我失望。

JSON结构如下:

{
    "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"
                }
            ]
        }
    ]
}

4 个答案:

答案 0 :(得分:1)

以下示例应该有效

var library = {
    "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"
                }
            ]
        }
    ]
};


//Some test user answers, can change these to test other answers
var answers = ['B', 'C'];

//initialize total score
var score = 0;

//loop through each user answer
answers.forEach(function(answer, index) {

    //look at the answer in the question library at the same index as 
    //the user answer, and find the answer in that array with value 
    //that  equals user answer, then access the weight of that object, 
    //cast to number, and add to score
    score += Number(library.questions[index].answers.find(function(question) { return question.value === answer }).weight)
});

//score should print 4 if user answers are "B" and "C"
console.log(score);

答案 1 :(得分:1)

您可以使用以下功能获得答案及其相应重量的总和。数据是有问题的对象。请检查此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);

答案 2 :(得分:1)

您可以使用Array.reduce()轻松完成此操作。运行下面的示例并阅读注释以获得解释。



function sumObjectArray(a) {
  //use reduce to iterate the array and keep a running total
  return a.reduce(function(prev, current) {
    //prev is previous result, or the empty object passed as a default
    //loop through all the items in current
    current.answers.forEach(function(item) {
      var value = item.value;
      var weight = Number(item.weight); //must convert to number to prevent string concatenation

      //if value is defined then add to it, otherwise set value to current value
      if (prev[value])
        prev[value] += weight;
      else
        prev[value] = weight;
    });

    //return updated object for next iteration through reduce()
    return prev;
  }, {}); //pass empty object as default value for prev
}

var input = [{
  "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"
  }]
}]

console.log(sumObjectArray(input));




答案 3 :(得分:1)

假设您通过名为userAnswer的列表跟踪用户的回答。您可以做的是使用reduce变量上的problem api(您的问题),得出总分。

reduce调用中,您还可以使用find api在其中找到答案对象。获得答案对象后,您只需将String中的权重值转换为Number,然后将其添加到reduce的累加器参数中。

示例:

var userAnswer = [ "A", "A" ];
var problem = {
    "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"
            }
        ]
    }
  ]
};

let score = problem.questions.reduce((accumulator, question, index) => {
    let score = question.answers.find((answer) => { return (answer.value === userAnswer[index]); });
    return accumulator += Number(score.weight);
}, 0);

console.log(`Total score ${score}`);

<强>输出:

  

总分4

如果您有兴趣,可以在此处参考reducefind的更多用法示例:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce