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

183
Visualizações
how convert my nested object to array in javascript

I have an object with nested objects. In this object, each objects having two or more sub-objects. I want to get together all sub-objects into an array of data. How to do with JavaScript?

 const category = {
    id: 1,
    title: "a",
    level: 2,
    __parent: {
      id: 2,
      title: "b",
      level: 1,
      __parent: {
        id: 3,
        title: "c",
        level: 0,
      }
    }
  };

The output I want is this:

   [{
    id: 1,
        title: "a",
        level: 2,
    __parent: null
    },
    {
     id: 2,
          title: "b",
          level: 1,
    __parent: null
    
    },
    {
      id: 3,
            title: "c",
            level: 0,
    __parent:null
    
    }]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

It Be some like this :

 const myArray = []
const category = ...;

function foo(obj){
    myArray.push({ 
         title:obj.title,
          ....
    })
    if (obj._parent)
        foo(obj._parent)
}
foo(category)
about 4 years ago · Juan Pablo Isaza Relatório

0

You essentially want to get the list of ancestors.

const ancestors = []
var parent = category
while (parent) {
  ancestors.push({
    id: parent.id,
    level: parent.level,
    __parent: null
  })
  parent = parent.__parent
}
about 4 years ago · Juan Pablo Isaza Relatório

0

use recursion to extract objects:

 const category = {
    id: 1,
    title: "a",
    level: 2,
    __parent: {
      id: 2,
      title: "b",
      level: 1,
      __parent: {
        id: 3,
        title: "c",
        level: 0,
      }
    }
  };
  
function extract(obj,arr=[]){
    arr.push({...obj,__parent:null})
    if(!obj.__parent){
        return arr
    }
    
    return extract(obj.__parent,arr)    
 }

 let result = extract(category)
 console.log(result)

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