Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda