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

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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