我有一个具有多级嵌套的对象数组。
const switches = [
{
orgId: "1111a7cd-0d58-11ef-83a2-06a19a0b1f5d",
orgName: "Management 1",
orgType: 2,
organisations: [],
features: [
{
name: "AdvancedAdminApprovalLevels",
type: "feature",
category: "Management Features",
value: false,
},
{
name: "AdminCategoryApprovalByRole",
type: "feature",
category: "Management Features",
value: false,
},
],
},
{
orgId: "2222a7cd-0d58-11ef-83a2-06a19a0b1f5d",
orgName: "Management 2",
orgType: 2,
organisations: [
{
orgId: "33333f59a-4976-11ed-af5d-021feb88a3f6",
orgName: "Submanagement ",
orgType: 2,
features: [
{
name: "AdvancedAdminApprovalLevels",
type: "feature",
category: "Management Features",
value: false,
},
{
name: "AdminCategoryApprovalByRole",
type: "feature",
category: "Management Features",
value: false,
},
],
},
],
features: [
{
name: "AdvancedAdminApprovalLevels",
type: "feature",
category: "Management Features",
value: false,
},
{
name: "AdminCategoryApprovalByRole",
type: "feature",
category: "Management Features",
value: false,
},
],
},
{
orgId: "4444a7cd-0d58-11ef-83a2-06a19a0b1f5d",
orgName: "Management 3",
orgType: 2,
organisations: [],
features: [
{
name: "AdvancedAdminApprovalLevels",
type: "feature",
category: "Management Features",
value: false,
},
{
name: "AdminCategoryApprovalByRole",
type: "feature",
category: "Management Features",
value: false,
},
],
},
];
我想要的是将其映射到新数组的函数,其中如果提供的字符串 === 特征数组对象中的名称,则值应更改为参数中提供的值。
所以如果我像这样调用函数
handleTopLevelToggle('AdvancedAdminApprovalLevels', true);
我应该返回相同的嵌套数组,但在所有嵌套级别上,将所有名称为“AdvancedAdminApprovalLevels”的值更改为 true。
我开始使用的解决方案是
const handleTopLevelToggle = (value, fSwitch) => {
const mappedArray = switches.map((swtch) => {
swtch.features.map((feature) => {
if (feature.name === fSwitch) {
return { ...swtch, value: value };
}
return swtch;
});
});
return mappedArray;
};
您当前的解决方案处于正确的轨道上,但存在一些问题。
修改功能:
const handleTopLevelToggle = (fSwitch: string, value: boolean) => {
const mapFeatures = (features) => {
return features.map((feature) => {
if (feature.name === fSwitch) {
return { ...feature, value: value };
}
return feature;
});
};
const mapOrganisations = (organisations) => {
return organisations.map((org) => {
return { ...org, features: mapFeatures(org.features) };
});
};
const mappedArray = switches.map((swtch) => {
return {
...swtch,
features: mapFeatures(swtch.features),
organisations: mapOrganisations(swtch.organisations),
};
});
return mappedArray;
};