从表中动态地向charts.js添加数据

时间:2017-06-02 12:04:54

标签: javascript json chart.js

首先,我想使用两个JSON数组计算出现次数:

问题表作为答案选择:

{["Answer1","Answer2","Answer3","Answer4", ...]}

结果表作为答案:

{["Answer1","Answer1","Answer1","Answer1","Answer1","Answer2","Answer2","Answer2"]}

我需要弄清楚如何动态计算它们

{ 
  Answer1: 5,
  Answer2: 3,
  Answer3: 0,
  Answer4: 0
}

然后我还需要将它们传递给这个Charts.js(标签和数据)

data: {
  labels: ['Answer1', 'Answer2', 'Answer3', 'Answer4', ...]
  datasets: [{
    label: ': votes',
    data: ["5", "3", "0", "0", ...],
    backgroundColor: 'rgba(0,102,204,0.2)',
    borderColor: 'rgba(0,102,204,1)',
    borderWidth: 1
  }]
},

提前致谢:)

2 个答案:

答案 0 :(得分:0)

此功能可以根据您的答案和结果计算您的答案:

function dynamicCounter(answers,results){
    return answers.map( (a) => {
        var nb = 0;
        results.forEach( (r) => { if(a === r)nb++ } ); 
        return { [a] : nb }
    })
}

如果您只想将结果提供给chartjs(作为数据):

function results(answers,results){
    return answers.map( (a) => {
        var nb = 0;
        results.forEach( (r) => { if(a === r)nb++ } ); 
        return nb;
    })
}

这里有一个工作的jsfiddle https://jsfiddle.net/wanhe6rs/1/

答案 1 :(得分:0)

此函数将返回ChartJS所需的数据:

function getCountData(choices, results) {
  var counts = {};
  var data = [];

  choices.forEach(function(c) {
    counts[c] = 0;
  });

  results.forEach(function(r) {
    counts[r] += 1;
  });

  Object.keys(counts).forEach(function(c) {
    data.push(counts[c]);
  });

  return data;
}

var choices = ['Answer1', 'Answer2', 'Answer3', 'Answer4', 'Answer5'];
var results = ["Answer1", "Answer1", "Answer1", "Answer1", "Answer1", "Answer2", "Answer2", "Answer2"];

console.log(getCountData(choices, results));

您可以像ChartJS一样使用上述功能:

data: {
  labels: choices,
  datasets: [{
    label: ': votes',
    data: getCountData(choices, results),
    // ...
  }]
},