Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!