Home > Net >  Passing objects as props while retaining keys, using object map
Passing objects as props while retaining keys, using object map

Time:06-19

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.

CodePudding user response:

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>
);

CodePudding user response:

Another answer was already given but I would like to propose a simpler solution. You can just spread your object keys on the component, given the object keys and component props are named equally: https://kevinyckim33.medium.com/jsx-spread-operator-component-props-meaning-3c9bcadd2493

  • Related