gpt4 book ai didi

javascript - 如何从 JSON 对象填充列表并创建 TreeView - JavaScript

转载 作者:行者123 更新时间:2023-12-02 23:26:49 25 4
gpt4 key购买 nike

我有一个复杂的 JSON 对象,需要按 parentId 进行分组。到目前为止,我在这段代码中实现了我想要的输出:

// My JSON Data
const locations = [
{
id: 1,
name: "San Francisco Bay Area",
parentId: null
},
{
id: 2,
name: "San Jose",
parentId: 3
},
{
id: 3,
name: "South Bay",
parentId: 1
},
{
id: 4,
name: "San Francisco",
parentId: 1
},
{
id: 5,
name: "Manhattan",
parentId: 6
},
];
function createTreeView(location) {
var tree = [],
object = {},
parent,
child;

for (var i = 0; i < location.length; i++) {
parent = location[i];

object[parent.id] = parent;
object[parent.id]["children"] = [];
}

for (var id in object) {
if (object.hasOwnProperty(id)) {
child = object[id];

if (child.parentId) {
object[child["parentId"]]["children"].push(child);
} else {
tree.push(child);
}
}
}
return tree;
}

我仅使用它将其显示为纯 JSON 数据

var root = createTreeView(locations);
document.body.innerHTML = "<pre>" + JSON.stringify(root, null, " ");

是否有可能将此 JSON 数据放入 <li> 中使用上面的代码

最佳答案

这里,我举了一个例子。查看 CreateUlTreeView 并确保您阅读了评论。

// My JSON Data
const locations = [
{
id: 1,
name: "San Francisco Bay Area",
parentId: null
},
{
id: 2,
name: "San Jose",
parentId: 3
},
{
id: 3,
name: "South Bay",
parentId: 1
},
{
id: 4,
name: "San Francisco",
parentId: 1
},
{
id: 5,
name: "Manhattan",
parentId: 6
},
];
function createTreeView(location) {
var tree = [],
object = {},
parent,
child;

for (var i = 0; i < location.length; i++) {
parent = location[i];

object[parent.id] = parent;
object[parent.id]["children"] = [];
}

for (var id in object) {
if (object.hasOwnProperty(id)) {
child = object[id];
// i made some changes here incase some element is missing so you dont get error and just append th tree insetad
if (child.parentId && object[child["parentId"]]) {
object[child["parentId"]]["children"].push(child);
} else {
tree.push(child);
}
}
}
return tree;
}


// here is how you build your UL treeview recursively
function CreateUlTreeView(items, parent){
var ul = document.createElement("ul");
if (parent)
parent.appendChild(ul);
items.forEach(function(x) {
var li = document.createElement("li");
var text = document.createElement("span");
text.innerHTML = x.name;
li.appendChild(text);
if (x.children && x.children.length>0)
CreateUlTreeView(x.children, li);
ul.append(li);
});
return ul;
}
var root = createTreeView(locations);

CreateUlTreeView(root,document.getElementById("container"))
<div id="container">

</div>

关于javascript - 如何从 JSON 对象填充列表并创建 TreeView - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56698859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com