[英]How can I create an unordered list in react based on array of objects?
I have an array of objects whose schema is something like this.我有一组对象,其模式是这样的。
[
{ text: 'Contents', level: 2 },
{ text: 'h2 Heading', level: 2 },
{ text: 'h3 Heading', level: 3 },
{ text: 'h4 Heading', level: 4 },
{ text: 'Heading', level: 2 },
]
I want to create an unordered list based on the levels of each object. So, for eg.我想根据每个 object 的级别创建一个无序列表。因此,例如。 the above array should be displayed as:上面的数组应该显示为:
<ul>
<li>Contents</li>
<li>
h2 Heading
<ul>
<li>
h3 Heading
<ul>
<li>h4 Heading</li>
</ul>
</li>
</ul>
</li>
<li>Heading</li>
</ul>
I can check for the next object if it has the same level as the previous one.我可以检查下一个 object 是否与前一个具有相同的级别。 And handle the queries accordingly, but is there a better solution?并相应地处理查询,但是有更好的解决方案吗? Or any solution that works properly.或者任何可以正常工作的解决方案。
Edit #1: Just now, I found a solution that was asked here around 13 years ago.编辑 #1:刚才,我找到了大约 13 年前在这里提出的解决方案。 I can style the elements giving it a perception of a nested list.我可以设计元素的样式,让它感觉像是一个嵌套列表。 Link: Produce heading hierarchy as ordered list链接: 将标题层次结构生成为有序列表
Still, if there is a better solution, please do reply.不过,如果有更好的解决方案,请回复。
This is a possible solution.这是一个可能的解决方案。 You can check this link for a reactive online code editor.您可以查看此链接以获取反应式在线代码编辑器。
const objects = [
{ text: "Contents", level: 2 },
{ text: "h2 Heading", level: 2 },
{ text: "h3 Heading", level: 3 },
{ text: "h4 Heading", level: 4 },
{ text: "Heading", level: 2 }
];
const getDisplayableObjects = () => {
const arr = [];
let targetArr;
for (const obj of objects) {
const { text, level } = obj;
switch (level) {
case 2:
arr.push({ text, children: [] });
break;
case 3:
targetArr = arr[arr.length - 1].children;
targetArr.push({ text, children: [] });
break;
case 4:
targetArr = arr[arr.length - 1].children;
targetArr = targetArr[targetArr.length - 1].children;
targetArr.push({ text, children: [] });
break;
default:
break;
}
}
return arr;
};
const App = () => {
return (
<>
{getDisplayableObjects().map(({ text, children }) => (
<ul>
<li>
{text}
{children.map(({ text, children }) => (
<ul>
<li>{text}</li>
{children.map(({ text, children }) => (
<ul>
<li>{text}</li>
</ul>
))}
</ul>
))}
</li>
</ul>
))}
</>
);
};
export default App;
Result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.