@osmos/arraytotree
Version:
transform flat array to tree structure
49 lines • 1.29 kB
JavaScript
// src/index.ts
function arrayToTree(nodes, option) {
const { idKey, parentKey, childrenKey, sortKey } = option;
const roots = [];
if (sortKey) {
nodes.sort((a, b) => a[sortKey] - b[sortKey]);
}
for (const node of nodes) {
if (!node[childrenKey]) {
node[childrenKey] = [];
}
}
for (const node of nodes) {
let parentId = parentKey.includes(".") ? parentKey.split(".").reduce((obj, key) => obj && obj[key], node) : node[parentKey];
if (parentId && typeof parentId === "object") {
parentId = parentId[idKey];
}
if (parentId === null || parentId === void 0) {
roots.push(node);
} else {
const parent = nodes.find((item) => item[idKey] === parentId);
if (parent) {
parent[childrenKey].push(node);
} else {
roots.push(node);
}
}
}
function findNodeById(id, nodes2) {
if (nodes2) {
for (const node of nodes2) {
if (node[idKey] === id) {
return node;
}
const foundNode = findNodeById(id, node[childrenKey]);
if (foundNode) {
return foundNode;
}
}
}
return null;
}
roots.findNodeById = (id) => findNodeById(id, roots);
return roots;
}
export {
arrayToTree
};
//# sourceMappingURL=index.mjs.map