【发布时间】:2019-11-04 00:49:49
【问题描述】:
我有一个复杂的 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> 中
【问题讨论】:
-
你能展示一个你想要的最终 html 应该是什么样子的示例吗?
-
所以您想将您的树显示为嵌套的
<ul>和<li>元素?目前还不够清楚是什么问题。顺便说一句,我尝试将您的createTreeView函数与给定的locations数组一起使用,但它引发了错误。 -
@nickzoum 这是我想要实现的示例 HTML:imgur.com/31mHGl6>
标签: javascript html arrays json