I have array of objects with a multi-level nesting.
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,
}],
}];
What I want is the function to map it to new array where if the string provided === name in features array objects then value should be changed to the value provided in parameter.
So if I call the function like
handleTopLevelToggle('AdvancedAdminApprovalLevels', true);
I should return the same nested arrays but with value changed to true for all the with name ‘AdvancedAdminApprovalLevels’, on all nested levels.
Te solution I’ve started with was
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;
};
4
Answers
Your current solution is on the right track, but it has a few issues.
will result in undefined values in your mappedArray.
handling the nested organisations array.
Revised Function:
You just need a simple recursive function:
Complete snippet:
You could use a recursive approach and have a look to arrays as values.
Depending on what needs to be changed the solution will differ. E.g. for a shallow change (all object references will stay the same) you could go with
If you need new object references (e.g. for a compare on object level) i’d go with: