[英]Map and display multiple Array inside an object - Reactjs
I have a JSON file which is nested to create dropdown mega menu levels, I am not sure how to map and render multiple levels of arrays and object to create a tree like structure. 我有一个嵌套的JSON文件来创建下拉超级菜单级别,我不确定如何映射和渲染多个级别的数组和对象以创建树状结构。
Below is my JSON Structure: 以下是我的JSON结构:
{
"megamenu": [
{
"name": "level1.1",
"link": "#"
},
{
"name": "level1.2",
"link": "#",
"level1.2.1": {
"A": [
{
"name": "A-one",
"link": "#"
}
],
"B": [
{
"name": "B-one",
"link": "#"
}
]
}
},
{
"name": "level1.3",
"link": "#",
"children": [
{
"name": "level1.3.1",
"link": "#",
"children": [
{
"name": "level1.3.1.1",
"link": "#"
}
]
},
{
"name": "level1.3.1.2",
"link": "#",
"children": [
{
"name": "level1.3.1.2",
"link": "#"
}
]
}
]
}
]
}
I am able to map first level like this: 我可以这样映射第一层:
let menuArray = [];
let menu = this.props.menu.megamenu
console.log(menu);
for (let key in menu) {
menuArray.push(menu[key]);
return (
<section>
<ul>
{this.props.menu.megamenu.map((menuitem, index) = > (
<div key={index}>
<li>{menuitem.name}</li>
</div>
))}
</ul>
</section>
);
}
But would like to map all the levels and display like below structure : 但想映射所有级别并按以下结构显示:
<ul>
<li>Level1.1
<li>
<li>Level1.2
<div className="dropdown">
<ul>
<li>A</li>
<li>B</li>
</ul>
<ul>
<li>A-one</li>
<li>b-one</li>
</ul>
</div>
</li>
</ul>
<li>
<li>Level1.3
<div className="dropdown">
<div className="col">
<h2>level1.3.1</h2>
<ul>
<li>level1.3.1.1</li>
</ul>
</div>
<div className="col">
<h2>level1.3.2</h2>
<ul>
<li>level1.3.1.2</li>
</ul>
</div>
</div>
</li>
<ul>
I have tried to explain in details for better understanding, any help would be appreciated. 我试图详细解释以便更好地理解,我们将不胜感激。
As you would change the structure to something like this, 当您将结构更改为类似的内容时,
{
"megamenu": [
{
"name": "level1.1",
"link": "#"
},
{
"name": "level1.2",
"link": "#",
"children": [
{
"name": "A-one",
"link": "#"
},
{
"name": "B-one",
"link": "#"
}
]
},
{
"name": "level1.3",
"link": "#",
"children": [
{
"name": "level1.3.1",
"link": "#",
"children": [
{
"name": "level1.3.1.1",
"link": "#"
}
]
},
{
"name": "level1.3.1.2",
"link": "#",
"children": [
{
"name": "level1.3.1.2",
"link": "#"
}
]
}
]
}
]
}
Which is quite obvious as adding new keys inside child object is a wrong way, now, you need a recursive function which will take care of this which can be something like this 这很明显,因为在子对象中添加新键是错误的方法,现在,您需要一个递归函数来处理此问题,这可能是这样的
getData = (menu) => {
return <div>
<li>{menu.name}</li>
{(menu.children !== undefined && menu.children.length > 0) && <ul>{
menu.children.map(data => {
return this.getData(data);
})
}
</ul>}
</div>
}
And inside render you can change to this 在内部渲染中,您可以更改为
return (
<section>
<ul>
{data.megamenu.map((menuitem, index) => (
this.getData(menuitem)
))}
</ul>
</section>
);
So, what we did is calling the recursive function getdata
. 因此,我们所做的就是调用递归函数getdata
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.