Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

73
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda