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

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

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 Relatório

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 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