简体   繁体   English

如何在chart.js中求和/除数组值?

[英]How to sum/divide array values in chart.js?

I have this variable to put in my chart:我有这个变量放在我的图表中:

var datiedu2 = {
            "labels": ['Lavori non terminati', 'Lavori in corso'],
            "datasets": 
                      [{
                           label: 'Numero',
                           data: [arrayItem['Value1'] + arrayItem['Value2']],
                           backgroundColor: 'rgb(255, 99, 132)',
                           borderWidth: 1
                      }]
               };

I can't get to make sum or division with array items.我无法对数组项进行求和或除法。 These belong to a variable whose structure is like:这些属于一个变量,其结构如下:

 var myJSON = [
  {
    "": 0,
    "Comune": "BONDENO",
    "PUNTEGGIOSCUOLA1516": 4.25,
    "Value 1": 63,
    "Value 2": 8,
    "Value 3": 17,
    "DANNO": 6,
    "Somma valori": 88,
  },
  {
    "": 1,
    "Comune": "CAVEZZO",
    "PUNTEGGIOSCUOLA1516": 3.75,
    "Value 1": 23,
    "Value 2": 2,
    "Value 3": 9,
    "DANNO": 8,
    "Somma valori": 34,

  }

What is the best option to do it?这样做的最佳选择是什么?

Thanks.谢谢。

Just loop over the json array and then add the values to the sum variable and then add it to chart.只需遍历 json 数组,然后将值添加到 sum 变量,然后将其添加到图表中。

This code will do:此代码将执行以下操作:

var sum=0;
for(item of myJSON)
{
    let subsum=item["Value 1"]+item["Value 2"]+item["Value 3"];
    sum+=subsum;
}

Then update the code like this:然后像这样更新代码:

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

Sums the properties Value 1 and Value 2对属性值 1 和值 2 求和

 var myJSON = [{ "": 0, "Comune": "BONDENO", "PUNTEGGIOSCUOLA1516": 4.25, "Value 1": 63, "Value 2": 8, "Value 3": 17, "DANNO": 6, "Somma valori": 88, }, { "": 1, "Comune": "CAVEZZO", "PUNTEGGIOSCUOLA1516": 3.75, "Value 1": 23, "Value 2": 2, "Value 3": 9, "DANNO": 8, "Somma valori": 34, } ]; function getSum(arr) { const sum = arr.reduce((acc, x) => acc + x['Value 1'] + x['Value 2'], 0); return sum; } const result = getSum(myJSON); console.log(result)

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

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