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

107
Vistas
Build JSON Tree from Array using node string

I am following the example from this link Build tree array from JSON in JavaScript to generate my desired tree output. What I wanted to do was to make the "name" property value as the property name itself and remove the code property from the result. I tried to play with it but I have a little knowledge on how it works.

Codepen Link: json tree

Here is my desired result:

[
    {
        "one": "default value",
        "children": [
            {
                "one one": "default value"
            },
            {
                "one two": "default value"
            }
        ]
    },
    {
        "two": "default value"
    },
    {
        "three": "default value"
    }
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Instead of using

el

build a new object with a computed property name and take the reference of map[el.code] later in

map[parent].children.push(map[el.code]);

const
    arr = [{ code: "1", name: "one" }, { code: "1.1", name: "one one" }, { code: "1.2", name: "one two" }, { code: "2", name: "two" }, { code: "3", name: "three" }],
    transformToTree = (arr, root = '') => {
         let map = {}, last = [root], level = 0;
         map[root] = {};
         arr.forEach(el => {
              let parent = root;
              while (level && last[level].length >= el.code.length) level--;
              parent = last[level];
              level++;
              last.length = level;
              last.push(el.code);
              map[el.code] = { [el.name]: 'default value' };
              map[parent].children = map[parent].children || [];
              map[parent].children.push(map[el.code]);
         });
         return map[root].children;
    };    
console.log(transformToTree(arr));
.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