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

125
Views
Given an array of objects, link the child objects to its parents

Lets say I have the following

let arr = 

    [
     {name: "el1", id: 1, parent_id: 0},
     {name: "el2", id: 2, parent_id: 1},
     {name: "el3",  id: 3, parent_id: 0},
     {name: "el4", id: 4, parent_id: 3},
     {name: "el5", id: 5, parent_id: 0},
     {name: "el6", id: 6, parent_id: 2},
    ]

This should result in an arrays as follows

[
 {name: "el1", id: 1, parent_id: 0, childs: [{name: "el2", id: 2, parent_id: 1, childs: [{name: "el6", id: 6, parent_id: 2}]}]},
 {name: "el3",  id: 3, parent_id: 0, childs: [{name: "el4", id: 4, parent_id: 3}},
 {name: "el5", id: 5, parent_id: 0},
]

I can do it for 1 level, but how about multiple leves? My pseudocode would be something like

//iterate the array
//if array[i] has a parent_id != 0, push the element into its corresponding parrent, and delete the pushed index

But how can I do that for infinite potential levels?

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

0

Try like below. Explanation is in comments.

let arr = [
     {name: "el1", id: 1, parent_id: 0},
     {name: "el2", id: 2, parent_id: 1},
     {name: "el3",  id: 3, parent_id: 0},
     {name: "el4", id: 4, parent_id: 3},
     {name: "el5", id: 5, parent_id: 0},
     {name: "el6", id: 6, parent_id: 2},
];

function addChild(obj) {
  // get childs and further retrieve its childs with map recursively
  let childs = arr.filter(a => a.parent_id == obj.id).map(addChild);
  
  // if childs are found then add childs in object 
  if (childs.length > 0) {
    return { ...obj, childs };
  }
  
  // if no child found then return object only
  return { ...obj };
}

// get childs for parent id = 0
let result = arr.filter(a => a.parent_id == 0).map(addChild);
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!