我有一组数据:
+----+---------+--------+---------------------+
| id | goal_id | saved | date |
+----+---------+--------+---------------------+
| 1 | 1 | 50.00 | 2020-12-24 02:35:04 |
| 2 | 2 | 100.00 | 2020-12-24 02:35:04 |
| 3 | 3 | 500.00 | 2020-12-24 02:35:04 |
| 4 | 3 | 10.00 | 2020-12-24 02:35:04 |
| 5 | 3 | 50.00 | 2020-12-24 02:35:04 |
| 6 | 3 | 300.00 | 2020-12-24 02:35:04 |
+----+---------+--------+---------------------+
属于另一个数据集:
+----+--------+------------+
| id | myGoal | goal |
+----+--------+------------+
| 1 | House | 1000000.00 |
| 2 | Car | 21000.00 |
| 3 | School | 13000.00 |
+----+--------+------------+
我已经把它映射到前端:
{saveData &&
saveData.map((saveItem) => {
return (
<div className="card">
<ul className="card__list" key={saveItem.id}>
<SaveCard key={saveItem.id} saveItem={saveItem} />
</ul>
</div>
);
})}
现在我正试图用他们受人尊敬的身份证对他们进行分组
const [goalRemainder, setGoalRemainder] = useState([saveItem]);
const saveID = goalRemainder.reduce((savedAmount, { goal_id, saved }) => {
(savedAmount[goal_id] = savedAmount[goal_id] || []).push(saved);
return savedAmount;
}, {});
我的输出看起来像:
{1: Array(1)} 1: [50]
{2: Array(1)} 2: [100]
{3: Array(1)} 3: [500]
{3: Array(1)} 3: [10]
{3: Array(1)} 3: [50]
{3: Array(1)} 3: [300]
相反,我想要:
{1: [50]}
{2: [100]}
{3:[500, 10, 50, 300]}
我的问题是,我哪里错了?
请参考以下代码:https://codesandbox.io/s/dreamy-dew-0vlj5?file=/src/App.js对于您的预期输出。
const saveItem = [
{
goal_id: 1,
saved: 1
},
{
goal_id: 1,
saved: 2
},
{
goal_id: 2,
saved: 3
},
{
goal_id: 3,
saved: 4
},
{
goal_id: 3,
saved: 1
}
];
const [goalRemainder, setGoalRemainder] = useState(saveItem); // no array brackets here
const savedAmount = {};
const saveID = goalRemainder.reduce((savedAmount, { goal_id, saved }) => {
(savedAmount[goal_id] = savedAmount[goal_id] || []).push(saved);
return savedAmount;
}, {});
console.log(saveID);
由于我没有看到您的完整代码,我不确定goalRemainder.reduce
在您的情况下是如何工作的。在我看来,只要Array.reduce
的使用遵循文档,我认为大多数逻辑都是好的。