JSFiddle - React, Tailwind, and code Playground
Heirarchal Data Tree | Heirarchally map children to parents given a flat array
by skibulk
JavaScript
var heirarchy = [{
id: 1,
parentId: 0,
label: 'colors',
}, {
id: 2,
parentId: 0,
label: 'shapes',
}, {
id: 3,
parentId: 1,
label: 'red',
}, {
id: 4,
parentId: 1,
label: 'green',
}, {
id: 5,
parentId: 3,
label: 'burgundy',
}, {
id: 6,
parentId: 3,
label: 'crimson',
}];
function buildTree(data, idKey, parentIdKey, idRoot) {
idKey = typeof idKey !== 'undefined' ? idKey : 'id';
parentIdKey = typeof parentIdKey !== 'undefined' ? parentIdKey : 'parentId';
idRoot = typeof idRoot !== 'undefined' ? idRoot : 0;
var i, id, pid, label, sorted = {};
for (i = 0; i < data.length; i++) {
id = data[i][idKey];
pid = data[i][parentIdKey];
if (!sorted[id]) {
sorted[id] = {
item: null,
children: {},
};
}
sorted[id].item = data[i];
if (!sorted[pid]) {
sorted[pid] = {
item: null,
children: {},
};
}
sorted[pid].children[id] = sorted[id];
}
return sorted[idRoot];
}
console.log(buildTree(heirarchy));