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

72
Views
Convert an array into nested Object

For exemple I have arr

  var arr = [
    {
     nID: 1,
     sLogin: 'user1',
     sParent: ''
    },
    {
     nID: 2,
     sLogin: 'user2',
     sParent: 'user1'
    },{
     nID: 3,
     sLogin: 'user3',
     sParent: ''
    },
 ]

And I need to make an Obj that's gonna look like this

{
 "user1": { 
     nID: 1,
     sLogin: 'user1',
     sParent: '',
     oChild: {
       "user2": {
         nID: 2,
         sLogin: 'user2',
         sParent: 'user1'
       }
    }
  },
  "user3": {
     nID: 3,
     sLogin: 'user3',
     sParent: ''}
  
}

We need to track "sLogin" and "sParent" and if it matches we should set into "oChild" to the parent's object and remove from the main

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

0

First I created a mapping object for users that have a parent so that I can easily pick the child from the mapping object. It will look like this

{
  user2: {
    nID: 2,
    sLogin: "user2",
    sParent: "user1"
  }
}

After that i did a reduce on the original array and picked from the mapping when sParentis not an empty string

var arr = [{nID: 1,sLogin: 'user1',sParent: ''},{nID: 2,sLogin: 'user2',sParent: 'user1'},{nID: 3,sLogin: 'user3',sParent: ''},]
 
 
const mapping = {}
arr.forEach(el => {if(el.sParent !== '') mapping[el.sLogin]=el})

const res = arr.reduce((acc,curr)=>{
    const {nID,sLogin,sParent} = curr
  if(sParent===''){
    acc[sLogin]=curr
  }
  else{
    acc[sParent]['oChild'] = {} 
    acc[sParent]['oChild'][sLogin] = mapping[sLogin]
  }
  
  return acc;
},{})

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

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!