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

140
Views
JavaScript: generar cadenas HTML a partir de un objeto de árbol con sangría

Necesitaba generar las cadenas HTML a partir de un objeto de árbol con la sangría adecuada. p.ej

 { children: [ { tag: 'div', children: [{ tag: 'span', children: ['bar1', 'bar2'] }] }, { tag: 'div', children: ['baz'] }, ], tag: 'body', }

se convertiría

 <body> <div> <span> bar1 bar2 </span> </div> <div> baz </div> </body>

Aquí está mi intento

 function generateHTMLFrom(tree) { const recur = (node, depth = 0, indent = ' ') => { if (!node.children) return node return [ `${indent.repeat(depth * 2)}`, `<${node.tag}>`, ...node.children.flatMap((child) => recur(child, depth + 1)), `${indent.repeat(depth * 2)}</${node.tag}>`, ] } return recur(tree).join('\n') }

Pero el formato en realidad está desordenado porque la sangría está mal.

Alguien me puede ayudar a arreglar esto?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Casi lo tienes. Recomendaría eliminar la complejidad de su recursividad para simplificarla (no es necesario, solo para una mejor legibilidad).

En lugar de multiplicar depth * 2 , podría inicializar su argumento con indent = ' ' . Y las dos primeras líneas de su matriz devuelta podrían combinarse de la misma manera que lo hizo para la etiqueta de cierre.

 `${indent.repeat(depth)}<${node.tag}>`

Y por último, pero no menos importante (su pequeño error real), el valor de retorno no debe ser un nodo, debe ser su nodo con una sangría:

 return `${indent.repeat(depth)}${node}`;

Terminarás con algo como esto:

 const tree = { tag: 'body', children: [ { tag: 'div', children: [ { tag: 'span', children: [ 'bar1', 'bar2' ] } ] }, { tag: 'div', children: [ 'baz' ] } ] }; function generateHTML (tree) { const recur = (node, depth=0, indent=' ') => { if (!node.children) { return `${indent.repeat(depth)}${node}`; } return [ `${indent.repeat(depth)}<${node.tag}>`, ...node.children.flatMap((child) => recur(child, depth + 1)), `${indent.repeat(depth)}</${node.tag}>` ]; }; return recur(tree).join('\n'); } console.log(generateHTML(tree));

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!