简体   繁体   English

如何在循环函数内对chart.js中的数组值求和?

[英]How to sum array value in chart.js inside loop function?

I have this function:我有这个功能:

click: function(e) {
  map.fitBounds(e.target.getBounds());

  myJSON.forEach(function (arrayItem) {
    if (arrayItem["Comune"] == e.target.feature.properties.NOME_COM.toUpperCase()) {
      $('.lead').html('');
      $('.lead').html('Comune di ' + arrayItem.Comune);
      $('#pulsante').html('');
      $('#pulsante').append('<div id="emptyred"><span style="opacity:0;">FMVPAFSB</span></div>')
      $('#pulsante').append('<div class="row" id="redditiButton"><div class="col-lg-6"><form><label class="radio-inline btn btn-danger"><input type="radio" id="generale" value="generale" name="radiored" autocomplete="off" checked> Generale</label><label class="radio-inline btn btn-danger"><input type="radio" id="dettaglio" value="dettaglio" name="radiored" autocomplete="off"> Dettaglio</label><label class="radio-inline btn btn-danger"><input type="radio" id="grafico3" value="grafico3" name="radiored" autocomplete="off"> Grafico3</label></form></div>')
      $('#chartContainer').append('<canvas id="Chartedu"><canvas>')

      var datiedu = {
        "labels": ['Lavori non terminati', 'Lavori in corso', 'Lavori terminati'],
        "datasets": [{
          label: 'Numero',
          data: [arrayItem['Value 1'], arrayItem['Value 2'], arrayItem['Value 3']],
          backgroundColor: ['rgb(255, 99, 132)', 'rgb(255, 51, 95)', 'rgb(255, 0, 55)'],
          borderWidth: 1
        }]
      };

      var datiedu2 = {
        "labels": ['Lavori non terminati', 'Lavori in corso'],
        "datasets": [{
          label: 'Numero',
          data: [I WANT SUM HERE],
          backgroundColor: 'rgb(255, 99, 132)',
          borderWidth: 1
        }]
      };

      function grafo(dati, opzioni) {
        var grafobase = document.getElementById('Chartedu').getContext('2d');
        new Chart(grafobase, {
          type: 'doughnut',
          data: dati,
          options: opzioni
        });
      };
      grafo(datiedu);
    }
  });
}

How do I sum arrayItem['Value 1'] and arrayItem['Value 2'] so that I can put it in the data of var datiedu2 ?我如何求和arrayItem['Value 1']arrayItem['Value 2']以便我可以把它放在 var datiedu2的数据中? It has to be inside the condition, but it doesn't work.它必须在条件内,但它不起作用。 If I try I obtain only the total sum of myJSON... which isn't useful.如果我尝试,我只会获得 myJSON 的总和……这是没有用的。

You can use reduce() method for this like:您可以使用reduce()方法,例如:

var datiedu2 = {
   "labels": ['Lavori non terminati', 'Lavori in corso'],
   "datasets": [{
      label: 'Numero',
      data: arrayItem.reduce((a, b) => a + ((b['Value 1'] || 0) + (b['Value 2'] || 0)), 0),
      backgroundColor: 'rgb(255, 99, 132)',
      borderWidth: 1
   }]
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM