[英]Iterating over deeply Nested JSON
鉴于我有一个大的 JSON 如下
{
"tab": [
{
"children": [
{
"children": [
{
"text": "some_string",
"href": "some_href",
"id": "inner_child_1"
},
{
"text": "some_string",
"href": "some_href",
"id": "inner_child_2"
}
],
"text": "some_string",
"href": "some_href",
"id": "first_child"
},
{
"children": [
{
"children": [
{
"children": [
{
"text": "some_string",
"href": "some_href",
"id": "more_1"
},
{
"text": "some_string",
"href": "some_href",
"id": "more_2"
}
],
"text": "some_string",
"href": "some_href",
"id": "inner_1"
},
{
"text": "some_string",
"href": "some_href",
"id": "inner_2"
}
],
"text": "some_string",
"href": "some_href",
"id": "inner_first_child"
},
{
"text": "some_string",
"href": "some_href",
"id": "inner_second_child"
}
],
"text": "some_string",
"href": "some_href",
"id": "second_child"
}
],
"text": "some_string",
"href": "some_href",
"id": "root_folder"
}
]
}
嵌套可以持续到多个级别
最终目标是遍历 JSON 并使用指定的 ID 创建文件夹。
如果一个对象有一个子数组,则创建一个带有 Id 的父文件夹并在子数组上循环,如果子数组中的任何条目嵌套了一个子数组,则创建另一个子文件夹并继续直到找不到子数组。 如果没有孩子继续下一次迭代。
最终的文件夹结构可能如下:
|--root_folder
|-- first_child
|-- inner_child_1
|-- inner_child_2
|-- second_child
|-- inner_first_child
|-- inner_1
|-- more_1
|-- more_2
|-- inner_2
|-- inner_second_child
谁能帮我弄清楚如何以最好的方式实现这一目标?
像这样的东西?
function parseData(obj, parent) { const item = document.createElement("li"), a = document.createElement("a"); a.href = obj.href; a.textContent = obj.text + " (id: " + obj.id + ")"; item.appendChild(a); if (!obj.children) item.id = obj.id; parent.appendChild(item); if (obj.children) { const folder = document.createElement("ul"); folder.id = obj.id; for(let i = 0; i < obj.children.length; i++) parseData(obj.children[i], folder); // loop through items inside folder parent.appendChild(folder); } } const data = { "tab": [ { "children": [ { "children": [ { "text": "some_string", "href": "some_href", "id": "inner_child_1" }, { "text": "some_string", "href": "some_href", "id": "inner_child_2" } ], "text": "some_string", "href": "some_href", "id": "first_child" }, { "children": [ { "children": [ { "children": [ { "text": "some_string", "href": "some_href", "id": "more_1" }, { "text": "some_string", "href": "some_href", "id": "more_2" } ], "text": "some_string", "href": "some_href", "id": "inner_1" }, { "text": "some_string", "href": "some_href", "id": "inner_2" } ], "text": "some_string", "href": "some_href", "id": "inner_first_child" }, { "text": "some_string", "href": "some_href", "id": "inner_second_child" } ], "text": "some_string", "href": "some_href", "id": "second_child" } ], "text": "some_string", "href": "some_href", "id": "root_folder" } ] }; for(let i = 0; i < data.tab.length; i++) parseData(data.tab[i], document.getElementById("main"));
<ul id="main"></ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.