简体   繁体   中英

React - How to get property of an object inside an object

I have an array of SidebarItems which accepts objects, inside the object there are 2 properties, name and route , I want to use name value as route value, but I am getting an error called Unexpected use of 'name' , here is my actual code

const SidebarItems = [
    {
        name: "Calendar",
        route: `/${name}`,
    },
];

export default SidebarItems;

You can't really reference the name like that. What you can do is to generate the array for example in the following way:

const SidebarItems = ['Calendar', 'Messages', 'Notifications'].map((itemName) => ({
   name: itemName,
   route: `/${itemName}`
}));

You need something like

const SidebarItems = ({ name, route }) => ([
    {
        name: "Calendar",
        route: `/${name}`,
    },
]);

export default SidebarItems;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM