【发布时间】:2020-12-13 20:32:49
【问题描述】:
我有一个问题,如何映射和减少这样的数组:
[
{
id: 1,
Price: 50,
Item: {id: 1, Name: "A"},
Date: {id: 1, Start: "202001"}
},
{
id: 2,
Price: 100,
Item: {id: 1, Name: "A"},
Date: {id: 2, Start: "202002"}
},
{
id: 3,
Price: 200,
Item: {id: 2, Name: "B"},
Date: {id: 1, Start: "202001"}
}
]
我正在用 React 编写一个应用程序,我想在表格中显示这些值。
它应该看起来像这样:
| ITEM | 202001 | 202002 |
|---|---|---|
| A | 50 | 100 |
| B | - | 200 |
我希望能够用数组做到这一点:
[
{
id: 1,
Item: {id: 1, Name: "A"},
Date: [{id: 1, Start: "202001",Price: "50"},{id: 2, Start: "202002",Price: "100"}]
},
{
id: 2,
Item: {id: 2, Name: "B"},
Date: {id: 1, Start: "202001",Price: "200"}
}
]
有什么建议可以满足我的需要吗?
【问题讨论】:
-
你到底想得到什么输出?
-
我插入了 Markdown 格式的表格,你可以看到我想要的结果
-
请看这篇文章。它有几乎相同的问题。 stackoverflow.com/a/34890276/9515661
-
尝试了以下,但它没有分组:
const tempData = [ { id: 1, Price: 50, Item: {id: 1, Name: "A"}, Date: {id: 1, Start: "202001"} }, { id: 2, Price: 100, Item: {id: 1, Name: "A"}, Date: {id: 2, Start: "202002"} }, { id: 3, Price: 200, Item: {id: 2, Name: "B"}, Date: {id: 1, Start: "202001"} } ] var groupBy = function(xs, key) { return xs.reduce(function(rv, x) { (rv[x[key]] = rv[x[key]] || []).push(x); return rv; }, {}); }; console.log(groupBy(tempData, 'Item.Name'));
标签: javascript arrays json reactjs api