const elementsArray = [
{ id: 1, name: "Hydrogen" },
{ id: 2, name: "Helium" },
{ id: 3, name: "Lithium" },
{ id: 4, name: "Beryllium" },
{ id: 5, name: "Boron" },
{ id: 6, name: "Carbon" },
{ id: 7, name: "Nitrogen" },
{ id: 8, name: "Oxygen" },
{ id: 9, name: "Fluorine" },
{ id: 10, name: "Neon" },
...
];
const nodeList = [];
const createNodeElement = (element) => {
const nodeElement = {
id: element.id,
name: element.name,
children: [],
parent: element.parent
};
return nodeElement;
};
const fillElementsArray = (elementsArray, rootNode) => {
elementsArray.forEach((element) => {
if (element.parent === rootNode.id) {
const childNode = rootNode.children.find((child) => child.id === element.id);
if (!childNode) {
rootNode.children.push(createNodeElement(element));
}
}
});
};
const fillTreeStructure = (elementsArray, rootNode) => {
fillElementsArray(elementsArray, rootNode);
if (rootNode.children.length > 0) {
rootNode.children.forEach((node) => {
fillElementsArray(elementsArray, node);
fillTreeStructure(elementsArray, node);
});
}
};
elementsArray.forEach((element) => {
if (!element.parent) {
const rootElement = createNodeElement(element);
fillTreeStructure(elementsArray, rootElement);
nodeList.push(rootElement);
}
});
console.table(nodeList);
console.log("🚩");
console.table(nodeList[0].children);
console.log("🚩");
console.table(nodeList[0].children[0].children);
console.log("🚩");
console.table(nodeList[0].children[0].children[0].children);