[英]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.