简体   繁体   中英

How to render nested map from JSON in React.JS?

I'm trying to render menu values from a JSON. Considering that this is a multilevel menu, I'm trying to do a nested map to render the full menu.

const menu = {
  data:[
  {
    title: "Home",
    child: [
      {
        title: "SubLevel1",
        child: {
          title: "SubSubLevel1"
        }
      },
      {
        title: "SubLevel2",
        child: [
          {title: "SubSubLevel1"},
          {title: "SubSubLevel2"}
        ]
      }
    ]
  },
  {
    title: "About",
  },
  {
    title: "Contact",
  }
]}

And here is the part when I use the map function:

const MenuNavigation = () => {
    return (
        {menu.data.map((item) => ( 
            <div>
                <ul>{item.title}</ul> 
                {item.map((sub, id) =>
                    <li>{sub.child[id].title}</li>
                )} 
            </div>
        ))}
    )
};

I managed to render main level for the menu (Home, About, Contact), but how can I print sublevel & subsublevel values?

Another question: Is there a way to map recursively a tree structure?

Try below:

The menu should be like this. Your menu had one issue in child of "SubLevel1" not defined inside an array.

  const menu = {
    data: [
      {
        title: "Home",
        child: [
          {
            title: "SubLevel1",
            child: [{
              title: "SubSubLevel1",
            }],
          },
          {
            title: "SubLevel2",
            child: [{ title: "SubSubLevel1" }, { title: "SubSubLevel2" }],
          },
        ],
      },
      {
        title: "About",
      },
      {
        title: "Contact",
      },
    ],
  };

Render it recursively like below. I have added a margin-left to see the levels properly.

  const renderMenu = (menu) => {
    return menu.map((item) => (
        <div style={{ marginLeft: '25px' }}>
            {item.title}
            {item.child && renderMenu(item.child)}
        </div>
    ))
  }

  return <div>{renderMenu(menu.data)}</div>;

输出

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