【发布时间】:2021-09-28 19:17:40
【问题描述】:
我正在用 reactjs 开发一个应用程序,我有数组:
array = [
{
"id": 1,
"categoryId": 2,
"period": "202101",
"type": "A",
"price": 100,
"discount": 0
},
{
"id": 2,
"categoryId": 2,
"period": "202102",
"type": "B",
"price": 300,
"discount": 20
},
{
"id": 3,
"categoryId": 2,
"period": "202103",
"type": "B",
"price": 200,
"discount": 70
},
{
"id": 4,
"categoryId": 2,
"period": "202104",
"type": "A",
"price": 100,
"discount": 50
},
]
我需要减少它以将其显示为表格:
我做了什么来显示每个时期的价格细节:
const items = array.reduce((acc, e) => {
if (!acc[e["categoryId"]]) {
acc[e["categoryId"]] = {
[e["period"]]: e["price"]
}
} else {
acc[e["categoryId"]][e["period"]] = e["price"]
}
return acc
}, {})
const periods = [...new Set(Object.keys(items).map(i => Object.keys(items[i])).flat())]
thead:
<tr>{dates.map(date => <th>{date}</th>)}</tr>
tbody:
Object.keys(items).map((item) => {
return (
<tr>
<td>{item}</td>
{periods.map((period) => <td>{items[item][period] || ''}</td>)}
</tr>
)
})
但它只显示每个period 的price。我还需要显示discount 和type。
需要什么改动,有什么建议吗?
【问题讨论】:
-
这能回答你的问题吗? How to group an array of objects by key
-
您能否添加一个您想要实现的结果的 json 表示形式?
标签: javascript reactjs datatable reduce