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

195
Views
Create nested array form an array of objects

I've an array of objects like this

  [
   {id :1, parent : null, title:test},
   {id :2, parent : 1, title:test2},
   {id :3, parent : 2, title:test3},
 .
 .
 .
  ]

and need function to arrange like this Output :

[
 {id :1, parent : null, title:test,
 sub:[
   {id :2, parent : 1, title:test2,
    sub :[
     {id :3, parent : 2, title:test3},
    ]
   },
 ]},
.
.
.
]

And so handle deep nested

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

something like this should do what you requested:

function nestArrays(arr) {
  let retval = [];
  for (let i = data.length - 1; i >= 0; i--) {
    const isLastElement = i < data.length - 1;
    retval.push(
      isLastElement
        ? {
            ...data[i],
            sub: [retval[retval.length - 1]],
          }
        : data[i]
    );
  }
  return retval;
}

about 4 years ago · Juan Pablo Isaza Report

0

You could iterate over your objects, try to find its the parent by ID, create a sub property on the parent if it does not exist, and finally push the current object to the sub array:

const objects = [
   { id: 1, parent: null, title: "test" },
   { id: 2, parent: 1, title: "test2" },
   { id: 3, parent: 2, title: "test3" },
   { id: 4, parent: 2, title: "test4" },
];

// This result array will contain all root objects, 
// e.g. those with `parent === null`
const roots = [];

for (const object of objects) {
  if (object.parent === null) {
    roots.push(object);
  }
  else {
    const parent = objects.find(o => o.id === object.parent);
    if (parent) {
      (parent.sub ||= []).push(object);
    }
  }
}

console.log(JSON.stringify(roots, null, 2));

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!