Home > Back-end >  How to replace the object array using simple filter and spread operators
How to replace the object array using simple filter and spread operators

Time:07-22

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. enter image description here

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.

  • Related