I need a suggestion for the below code. The objective here is to remove the specific array if the mentioned menuKey
is present.
Note: sdb.menu = 'account-links'
(Declared in another file);
const { menu = [] } = remainingConfig[sdb.menu]?.params || {};
const keysToRemove = ['sidebarReferAFriend'];
const filteredMenu = menu.filter(({ menuKey }: IMenuLink) => !keysToRemove.includes(menuKey));
How can I assign the filteredMenu
back to remainingConfig
object?
I tried with some spread operator options and it's not giving the existing same structure. So please provide some help here when you have some time.
The object structure will be like attached image.
CodePudding user response:
If you can directly assign to the remainingConfig[sdb.menu].params.menu
property, then since presumably you don't need to create the array if it's not there, only do the work if the array and everything leading up to it exists, then just assign back to menu
:
const menuConfigParams = remainingConfig[sdb.menu]?.params;
const menu = menuConfigParams?.menu;
if (menu) {
const keysToRemove = ['sidebarReferAFriend'];
menuConfigParams.menu = menu.filter(({ menuKey }/*: IMenuLink*/) => !keysToRemove.includes(menuKey));
}
If the remainingConfig
structure is deeply immutable, then we have to create a new object to replace it at every level of the nesting:
const menuConfig = remainingConfig[sdb.menu];
const menuConfigParams = menuConfig?.params;
let menu = menuConfigParams?.menu;
if (menu) {
const keysToRemove = ['sidebarReferAFriend'];
menu = menu.filter(({ menuKey }/*: IMenuLink*/) => !keysToRemove.includes(menuKey));
const newConfig = {
...remainingConfig,
[sdb.menu]: {
...menuConfig,
params: {
...menuConfig.params,
menu,
}
}
};
// ...then use whatever mechanism is in your environment to replace `remainingConfig`
// with `newConfig`...
}
Notice how at each level we're making a shallow copy of the structure via spread syntax.