Passing objects as props while retaining keys, using object map

Viewed 39

I have an object array, obj, like so:

{
    "root": [
        {
            "key": "mihome",
            "label": "home",
            "action": "url",
            "submenu": "none"
        },
        {
            "key": "signin",
            "label": "sign in",
            "action": "url",
            "submenu": "none"
        }
    ],
    "mainMenu": [
        {
            "key": "unito",
            "label": "unit o",
            "action": "url",
            "submenu": "none"
        },
        {
            "key": "unitt",
            "label": "unit t",
            "action": "url",
            "submenu": "none"
        }
    ]
}

Which I want to iterate out as components in React JS, using object map, like so:

return (
    <div className='menud'>
        {obj["root"] !== undefined ?
            Object.entries(obj).map(([key, menuItems]) => 
            <MenuList menuArray={obj[key]} key={key} menuKey={key} pcbClick={handleItemClick} />)
            : null
        }
    </div>
);

This works mostly as I intend, except I'm struggling to figure out how to retain the key name of each object, as they're mapped, which would require passing an object array rather than on array of objects. e.g. right now the first would receive a menuArray prop of:

[
        {
            "key": "mihome",
            "label": "home",
            "action": "url",
            "submenu": "none"
        },
        {
            "key": "signin",
            "label": "sign in",
            "action": "url",
            "submenu": "none"
        }
    ],

whereas I would like it to receive

{
root: [
        {
            "key": "mihome",
            "label": "home",
            "action": "url",
            "submenu": "none"
        },
        {
            "key": "signin",
            "label": "sign in",
            "action": "url",
            "submenu": "none"
        }
    ]
}

etc. as it iterates. I was looking into using JSON.stringify and just assigning key names and '{' characters but this feels like it's adding needless conversions.

2 Answers

You can do it like this:

return (
    <div className='menud'>
        {obj["root"] !== undefined ?
            Object.entries(obj).map(([key, menuItems]) => 
            <MenuList menuArray={{[key]: menuItems}} key={key} menuKey={key} pcbClick={handleItemClick} />)
            : null
        }
    </div>
);
Related