[英]How to sum array value in chart.js inside loop 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);
}
});
}
我如何求和arrayItem['Value 1']
和arrayItem['Value 2']
以便我可以把它放在 var datiedu2
的數據中? 它必須在條件內,但它不起作用。 如果我嘗試,我只會獲得 myJSON 的總和……這是沒有用的。
您可以使用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.