【发布时间】:2021-03-30 23:05:59
【问题描述】:
我有数组:
array = [
{
"id": 1,
"date": {
"id": 1,
"name": "202001"
},
"item": {
"id": 1,
"name": "I1"
},
"price": 100
},
{
"id": 2,
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 1,
"name": "I1"
},
"price": 200
},
{
"id": 3,
"date": {
"id": 2,
"name": "202002"
},
"item": {
"id": 2,
"name": "I2"
},
"price": 300
},
]
并且我希望能够显示如表所示的数据:
| ITEM | 202001 | 202002 | TOTAL |
|---|---|---|---|
| I1 | 100 | 200 | 300 |
| I2 | - | 300 | 300 |
| TOTAL | 100 | 500 | 600 |
我试过了
const items_dicc = array.reduce((acc, e) => {
if (!acc[e["item"]["name"]]) {
acc[e["item"]["name"]] = {
[e["date"]["name"]]: e["price"]
}
} else {
acc[e["item"]["name"]][e["date"]["name"]] = e["price"]
}
return acc
}, {})
const dates = [...new Set(Object.keys(items_dicc).map(i => Object.keys(items_dicc[i])).flat())]
要显示同一项目的每个日期的值,现在我需要上面的内容来计算小计和总计。
编辑:使用@sabbir.alam 答案
totalSumPerDate = {}; dates.forEach(date => { const sumOnDate = Object.values(items_dicc).reduce((acc, curr) => { acc = acc + (curr[date]?curr[date] : 0); 返回acc; }, 0); totalSumPerDate[[日期]] = sumOnDate; });
totalSum = Object.values(totalSumPerDate).reduce((acc, curr) => acc+curr, 0);
sumPerItem = {}; Object.keys(items_dicc).forEach(key => { const sum = Object.values(items_dicc[key]).reduce((acc, curr) => acc + curr, 0); sumPerItem[[key]] = 总和; });
我做到了
<table>
<thead>
<tr>
<th>ITEM</th>
{dates.map(date => <th>{date}</th>)}
<th>TOTAL</th>
</tr>
</thead>
<tbody>
{
Object.keys(items_dicc).map((item) => {
return (
<tr>
<td>{item}</td>
{dates.map((date) => <td>{items_dicc[item][date] || ''}</td>)}
{Object.values(sumPerItem).map((elem,i) => <td>{elem}</td>)}
</tr>
)
})
}
<tr>
<td>TOTAL</td>
{Object.values(totalSumPerDate).map((elem,i) => <td>{elem}</td>)}
<td>{totalSum}</td>
</tr>
</tbody>
</table>
我需要更正小计的显示方式。
我该怎么做,建议?
【问题讨论】:
标签: javascript arrays json reactjs datatables