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

141
Vistas
generar una estructura similar a un árbol usando una cadena separada por puntos

Lucho con la estructura del árbol. :(

Me gustaría hacer un árbol siguiendo la siguiente interfaz.

 export type Tree = Array<TreeNode>; export interface TreeNode { label: string; type: 'folder' | 'file'; children: Array<TreeNode> | string; }

Por ejemplo,

Tengo un archivo JSON como este

 { "common.header.title": "Header Title", "common.footer.btn": "Footer button", "common.footer.btn.submit": "Footer Submit", "apage.title": "apage Title" }

Mi resultado esperado es así.

 const out = [ { label: 'apage', type: 'folder', children: [ { label: 'title', type: 'file', children: 'apage Title' } ] }, { label: 'common', type: 'folder', children: [ { label: 'footer', type: 'folder', children: [ { label: 'btn', type: 'file', children: 'Footer button' }, { label: 'btn', type: 'folder', children: [{ label: 'submit', type: 'file', children: 'Footer Submit' }] }, ] }, { label: 'header', type: 'folder', children: [{ label: 'title', type: 'file', children: 'Header Title' }] } ] } ]

He visto algunos casos similares en SO, pero no pude referirme y desarrollarme con esos casos.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Puede buscar las etiquetas deseadas y verificar si children son una matriz, luego use este objeto para buscar en la matriz anidada.

Finalmente empuje un nuevo objeto.

 const data = { "common.header.title": "Header Title", "common.footer.btn": "Footer button", "common.footer.btn.submit": "Footer Submit", "apage.title": "apage Title" }, result = Object .entries(data) .sort(([a], [b]) => a.localeCompare(b)) .reduce((r, [path, children]) => { const keys = path.split('.'), label = keys.pop(); keys .reduce((t, label) => { let temp = t.find(o => o.label === label && Array.isArray(o.children)); if (!temp) t.push(temp = { label, type: 'folder', children: [] }); return temp.children; }, r) .push({ label, type: 'file', children }); return r; }, []); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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