Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!