如何从JSON对象-JavaScript填充列表并创建树视图
我有一个复杂的JSON对象,它需要按如何从JSON对象-JavaScript填充列表并创建树视图,javascript,html,arrays,json,Javascript,Html,Arrays,Json,我有一个复杂的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:
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
},
];
函数createTreeView(位置){
var-tree=[],
对象={},
父母亲
小孩
对于(变量i=0;i
我只是使用
var root = createTreeView(locations);
document.body.innerHTML = "<pre>" + JSON.stringify(root, null, " ");
var root=createTreeView(位置);
document.body.innerHTML=“”+JSON.stringify(root,null,”);
// <LIST>.toTree(<FUNCTION TO GET ID>, <FUNCTION TO GET PARENT ID>);
var tree = locations.toTree(location => location.id, location => location.parentId);
// createTreeView(<TREE>, <FUNCTION TO GET NAME>);
document.body.appendChild(createTreeView(tree, location => location.name)).id = "myUL";
有没有可能使用上面的代码将这个JSON数据放在
中呢。
请查看CreateUlTreeView
,并确保阅读了注释
//我的JSON数据
常数位置=[
{
id:1,
名称:“旧金山湾区”,
parentId:null
},
{
id:2,
名称:“圣何塞”,
家长编号:3
},
{
id:3,
名称:“南湾”,
父ID:1
},
{
id:4,
名称:“旧金山”,
父ID:1
},
{
id:5,
姓名:“曼哈顿”,
家长编号:6
},
];
函数createTreeView(位置){
var-tree=[],
对象={},
父母亲
小孩
对于(变量i=0;i0)
CreateUlTreeView(x.children,li);
ul.附加(li);
});
返回ul;
}
var root=createTreeView(位置);
CreateUlTreeView(根目录,document.getElementById(“容器”))
在这里,我举了一个例子。
请查看CreateUlTreeView
,并确保阅读了注释
//我的JSON数据
常数位置=[
{
id:1,
名称:“旧金山湾区”,
parentId:null
},
{
id:2,
名称:“圣何塞”,
家长编号:3
},
{
id:3,
名称:“南湾”,
父ID:1
},
{
id:4,
名称:“旧金山”,
父ID:1
},
{
id:5,
姓名:“曼哈顿”,
家长编号:6
},
];
函数createTreeView(位置){
var-tree=[],
对象={},
父母亲
小孩
对于(变量i=0;i0)
CreateUlTreeView(x.children,li);
ul.附加(li);
});
返回ul;
}
var root=createTreeView(位置);
CreateUlTreeView(根目录,document.getElementById(“容器”))
这是一个相当抽象的解决方案。您可以相当容易地重用它 触发整个树的部分是:
/.toTree(,);
var-tree=locations.toTree(location=>location.id,location=>location.parentId);
//createTreeView(,);
document.body.appendChild(createTreeView(tree,location=>location.name)).id=“myUL”;
Object.defineProperty(Array.prototype,“toTree”{
可配置:false,
可写:false,
值:函数(getKey、getParentKey){
var list=JSON.parse(JSON.stringify(this));
var root={};
对于(变量索引=0;索引// <LIST>.toTree(<FUNCTION TO GET ID>, <FUNCTION TO GET PARENT ID>);
var tree = locations.toTree(location => location.id, location => location.parentId);
// createTreeView(<TREE>, <FUNCTION TO GET NAME>);
document.body.appendChild(createTreeView(tree, location => location.name)).id = "myUL";