I have a complex JSON Object that needs to be grouped by parentId.
So far I achieved my desired output within this code:
// 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;
}
I am only displaying it as plain JSON Data using
var root = createTreeView(locations);
document.body.innerHTML = "<pre>" + JSON.stringify(root, null, " ");
Is there any possible to put this JSON data inside the <li> using the code above
<ul>and<li>elements? It's not clear enough what is the problem. BTW, I tried using yourcreateTreeViewfunction with the givenlocationsarray and it threw an error.