use*_*779 0 javascript jquery json
我想从 JSON 中获取数据的总和。我已经创建了 JSON 数据的表格视图,并且想要获取单个行的总和。我想得到week1, week2, week3, 和的总和week4。
const input = {
"data_report": [{
"data": [1, 2, 0, 3],
"label": "Test1",
"backgroundColor": "blue"
},
{
"data": [3, 4, 2, 5],
"label": "test2",
"backgroundColor": "#a3eaae"
},
{
"data": [2, 3, 1, 4],
"label": "test3",
"backgroundColor": "#37bd11"
},
{
"data": [1, 2, 0, 3],
"label": "test4",
"backgroundColor": "#43bee3"
},
{
"data": [1, 2, 0, 3],
"label": "test5",
"backgroundColor": "#a3eaae"
},
{
"data": [0, 1, 0, 2],
"label": "test6",
"backgroundColor": "#1195bd"
},
{
"data": [0, 1, 0, 2],
"label": "test7",
"backgroundColor": "#aeb5b7"
},
{
"data": [1, 2, 0, 3],
"label": "test8",
"backgroundColor": "pink"
}
],
"weeks": ["Week 1 ", "Week 2 ", "Week 3 ", "Week 4 "]
}
let thString = input.weeks.reduce((res, h) => res + '<th>' + h + '</th>', "<th></th>");
$('#thead').html(thString);
input.data_report.forEach(tr => {
const trString = "<td>" + tr.label + "</td>" + tr.data.reduce((res, d) => res + '<td>' + d + '</td>', "");
$('#tbody').append("<tr>" + trString + "</tr>");
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead id="thead"></thead>
<tbody id="tbody"></tbody>
<tbody id="tfooter"></tbody>
</table>Run Code Online (Sandbox Code Playgroud)
您可以通过对weeks值进行嵌套累积来获取页脚,对每个data数组中的相应值求和:
const input = {
"data_report": [{
"data": [1, 2, 0, 3],
"label": "Test1",
"backgroundColor": "blue"
},
{
"data": [3, 4, 2, 5],
"label": "test2",
"backgroundColor": "#a3eaae"
},
{
"data": [2, 3, 1, 4],
"label": "test3",
"backgroundColor": "#37bd11"
},
{
"data": [1, 2, 0, 3],
"label": "test4",
"backgroundColor": "#43bee3"
},
{
"data": [1, 2, 0, 3],
"label": "test5",
"backgroundColor": "#a3eaae"
},
{
"data": [0, 1, 0, 2],
"label": "test6",
"backgroundColor": "#1195bd"
},
{
"data": [0, 1, 0, 2],
"label": "test7",
"backgroundColor": "#aeb5b7"
},
{
"data": [1, 2, 0, 3],
"label": "test8",
"backgroundColor": "pink"
}
],
"weeks": ["Week 1 ", "Week 2 ", "Week 3 ", "Week 4 "]
}
let thString = input.weeks.reduce((res, h) => res + '<th>' + h + '</th>', "<th></th>");
$('#thead').html(thString);
input.data_report.forEach(tr => {
const trString = "<td>" + tr.label + "</td>" + tr.data.reduce((res, d) => res + '<td>' + d + '</td>', "");
$('#tbody').append("<tr>" + trString + "</tr>");
});
const tfString = input.weeks.reduce((res, _, i) => res + '<td>' + input.data_report.reduce((a, v) => a + v.data[i], 0) + '</td>', '<td>Total</td>');
$('#tfooter').append('<tr>' + tfString + '</tr>');Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead id="thead"></thead>
<tbody id="tbody"></tbody>
<tbody id="tfooter"></tbody>
</table>Run Code Online (Sandbox Code Playgroud)