Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

241
Vistas
Cómo convertir datos sin procesar en una estructura jerárquica

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", }, ], }, ], }, ], }, ], }, ];
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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));

about 4 years ago · Juan Pablo Isaza Denunciar

0

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));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda