Tengo datos sin procesar de la tabla de la base de datos que no tienen una relación directa entre sí. Pero tengo un conjunto de claves que nos da el orden de la jerarquía en nuestros datos.
Intenté algo como esto . Pero no se pudo obtener el resultado deseado.
Datos de entrada
const data = { item1: { chancellor: "my-chancellor-1", viceChancellor: "my-vice-chancellor-1", headProfessor: "my-head-professor-1", student: "student-1", intern: null, }, item2: { chancellor: "my-chancellor-1", viceChancellor: "my-vice-chancellor-1", headProfessor: "my-head-professor-1", student: null, intern: null, }, item3: { chancellor: "my-chancellor-1", viceChancellor: "my-vice-chancellor-1", headProfessor: "my-head-professor-1", student: "student-2", intern: null, }, item4: { chancellor: "my-chancellor-1", viceChancellor: "my-vice-chancellor-1", headProfessor: "my-head-professor-1", student: "student-3", intern: "intern-1", }, }Como dije, tenemos claves para identificar la jerarquía. Supongamos que las llaves son
const keyArray = ["chancellor", "viceChancellor", "headProfessor", "student", "intern"]
¿Cómo podemos obtener una salida en una estructura jerárquica?
Producción
[ { keyName: "chancellor", name: "my-chancellor-1", children: [ { keyName: "viceChancellor", name: "my-vice-chancellor-1", children: [ { keyName: "headProfessor", name: "my-head-professor-1", children: [ { keyName: "student", name: "student-1", }, { keyName: "student", name: "student-2", }, { keyName: "student", name: "student-3", children: [ { keyName: "intern", name: "intern-1", }, ], }, ], }, ], }, ], }, ];Encuentre el programa de solución, es un poco detallado, ya que no usé ninguna función de ES6. pero todavía funciona según las expectativas lógicamente.
const data = { item1: { chancellor: "my-chancellor-1", viceChancellor: "my-vice-chancellor-1", headProfessor: "my-head-professor-1", student: "student-1", intern: null, }, item2: { chancellor: "my-chancellor-1", viceChancellor: "my-vice-chancellor-1", headProfessor: "my-head-professor-1", student: null, intern: null, }, item3: { chancellor: "my-chancellor-1", viceChancellor: "my-vice-chancellor-1", headProfessor: "my-head-professor-1", student: "student-2", intern: null, }, item4: { chancellor: "my-chancellor-1", viceChancellor: "my-vice-chancellor-1", headProfessor: "my-head-professor-1", student: "student-3", intern: "intern-1", }, }; const keyArray = ["chancellor", "viceChancellor", "headProfessor", "student", "intern"] let output = []; let parent = null; Object.keys(data).forEach(dk => { parent = output.find(el => el.name == data[dk][keyArray[0]]); keyArray.forEach(kele => { if (!data[dk][kele]) { return; } let child = { "keyName": kele, "name": data[dk][kele] }; if (!parent) { output.push(child); parent = child; } else { if (!parent.children) parent.children = []; let alreadyPresentChild = parent.children.find(chl => chl.name == child.name); if (parent.keyName != child.keyName) { if (!alreadyPresentChild) { parent.children.push(child); parent = child; } else { parent = alreadyPresentChild; } } } }); }); console.log(JSON.stringify(output));Puede construir la jerarquía de la siguiente manera. Al mantener un mapa, codificado por ruta, puede verificar rápidamente si ya tiene un nodo para el valor actual o si necesita crear uno y agregarlo a la lista de elementos secundarios del padre:
function createHierarchy(data) { let tree = { children: [] }; let keys = {}; for (let item of Object.values(data)) { let node = tree; let key = ""; for (let keyName of ["chancellor", "viceChancellor", "headProfessor", "student", "intern"]) { let name = item[keyName]; if (name == null) break; key += "/" + name; let child = keys[key]; // Fast lookup if (!child) { child = keys[key] = { keyName, name }; (node.children ??= []).push(child); } node = child; } } return tree.children; } // Demo const data = {item1: {chancellor: "my-chancellor-1",viceChancellor: "my-vice-chancellor-1",headProfessor: "my-head-professor-1",student: "student-1",intern: null,},item2: {chancellor: "my-chancellor-1",viceChancellor: "my-vice-chancellor-1",headProfessor: "my-head-professor-1",student: null,intern: null,},item3: {chancellor: "my-chancellor-1",viceChancellor: "my-vice-chancellor-1",headProfessor: "my-head-professor-1",student: "student-2",intern: null,},item4: {chancellor: "my-chancellor-1",viceChancellor: "my-vice-chancellor-1",headProfessor: "my-head-professor-1",student: "student-3",intern: "intern-1",},}; console.log(createHierarchy(data));