gpt4 book ai didi

arrays - 如何在 React/Redux 代码中分组(前端新手)?

转载 作者:行者123 更新时间:2023-12-04 09:31:20 25 4
gpt4 key购买 nike

我很难在我的 React/Redux 代码中运行这个函数。我对 React 相当陌生(主要在后端工作),所以我不确定为什么它没有按预期运行。它在正确的地方吗?我也无法找到 console.log 在控制台中打印的位置,因为控制台设置了上一个操作、操作、下一个状态模式......
我在我的“actions.js”中定义了这个函数(稍后也会调用它):

const groupBy = (array, key) => {
return array.reduce((result, currentValue) => {(
result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
return result;
}, {});
};
这里是调用函​​数的地方(同一个文件):
export function getAlerts() {
return dispatch => {
api.get('notifications', (response) => {
const grouped = groupBy(response.results.data, 'email');
dispatch(updateFetchedAlerts(grouped));
}, (error) => {
console.warn(error);
})
}
}
输入 response.results.data 如下所示:
[{"email": test@email.com, "is_active": true, "alert_id": 1, "pk": 1}, 
{"email": test@email.com, "is_active": true, "alert_id": 2, "pk": 2},
{"email": different@email.com, "is_active": true, "alert_id": 1, "pk": 3}]

我希望它看起来像这样:
[{"test@email.com": [{"is_active": true, "alert_id": 1, "pk": 1}, 
{"is_active": true, "alert_id": 2, "pk": 2}],
"different@email.com": [{"is_active": true, "alert_id": 1, "pk": 3}]}]
但它似乎没有运行这个功能,我重新运行了 yarn build 并使用了隐身...
更新:此功能实际上有效!谢谢大家。 redux 开发人员工具非常有用。现在第二个问题是我需要添加我自己的 key ......所以理想的结果应该是这样的。最好没有 lodash!:
[{"email": "test@email.com",
"alerts": [{"is_active": true, "alert_id": 1, "pk": 1},
{"is_active": true, "alert_id": 2, "pk": 2}]},
{"email": "different@email.com",
"alerts": [{"is_active": true, "alert_id": 1, "pk": 3}]}]

最佳答案

您可以采用与用于分组的相同函数来生成形状对象

{ [string]: object[] }
使用 Object.entries允许您将其转换为键值对数组,您可以将其映射到具有形状的对象数组
{
email: string,
alerts: object[],
}
功能更新
const groupBy = (array, key) =>
array.reduce((result, { [key]: k, ...rest }) => {
(result[k] = result[k] || []).push(rest);
return result;
}, {});

const groupDataBy = (array, key) =>
Object.entries(groupBy(array, key)).map(([email, alerts]) => ({
email,
alerts
}));
map函数回调 ([email, alerts]) => ({ email, alerts })使用数组解构来分配 [key, value]的数组到命名变量 emailalerts , 和对象速记符号来创建一个带有为变量命名的键的对象。

const data = [{
"email": "test@email.com",
"is_active": true,
"alert_id": 1,
"pk": 1
},
{
"email": "test@email.com",
"is_active": true,
"alert_id": 2,
"pk": 2
},
{
"email": "different@email.com",
"is_active": true,
"alert_id": 1,
"pk": 3
}
];

const groupBy = (array, key) =>
array.reduce((result, { [key]: k, ...rest }) => {
(result[k] = result[k] || []).push(rest);
return result;
}, {});

const groupDataBy = (array, key) =>
Object.entries(groupBy(array, key)).map(([email, alerts]) => ({
email,
alerts
}));

const res = groupDataBy(data, 'email');

console.log(res)

关于arrays - 如何在 React/Redux 代码中分组(前端新手)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62827524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com