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

145
Visualizações
I have an object that contains the following data. How can I get all the data in the title key using the recursive function?

I have an object that contains the following data. How can I get all the data in the title key using the recursive function? I want a function return a array include a, b, c, d, e, f

{
                children: [
                    {
                        children: [
                            {
                                children: [],
                                title: "a"
                            }
                        ],
                        title: "b"
                    },
                    {
                        children: [
                            {
                                children: [],
                                title: "c"
                            },
                            {
                                children: [],
                                title: "d"
                            }
                        ],
                        title: "e"
                    }
                ],
                title: "f"
            }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can do something like this:

function drill(t, n) { 
    if (n.length > 0) { 
        for (let elem of n) { 
            t.push(elem.title); 
            drill(t, elem.children) 
        } 
    } 
    return t 
}

As @rickhg12hs did here

about 4 years ago · Juan Pablo Isaza Relatório

0

Following a solution using modern syntax. extractTitles recursively produces arrays of titles as long as there are children and reduces them to a single array.

const extractTitles = (arr) =>
  arr.reduce((prev, { children, title }) => [...prev, title, ...(children.length ? extractTitles(children) : [])], []);

extractTitles(tree);

Or you can use flatmap.

const extractTitles = ({ title, children = [] }) =>
  [title, ...children.flatMap(extractTitles)];

extractTitles(tree);
// ["f","b","a","e","c","d"]
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