JSFiddle - React, Tailwind, and code Playground
by Dmitri Ganenco
JavaScript
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
},
];
/*
const arr = locations.reduce((a,c) => {
}, []) */
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;
}
var root = createTreeView(locations);
document.body.innerHTML = "<pre>" + JSON.stringify(root, null, " ");