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

97
Visualizações
How iterate with help of recursion array of nested objects where property of object can have array of neste objects and replace property

I understand how recursion works, but I stuck with problem iterate throw this data view and replace all propertirties that called innerArray with subArray

I have next data view

const data = [
  {name: 'First', innerArray: [{name: InnerFirst, innerArray: []}]},
  {name: 'Second', innerArray: []}
]

And I try to transform in to next view

const data = [
  {name: 'First', subArray: [{name: InnerFirst, subArray: []}]},
  {name: 'Second', subArray: []}
]

There are another ways to make it, but how solve this task with recursion appoach?

function transformData = (data) => {
  for(let i =0; i< data.length; i++) {
   if(data[i].innerArray && data[i].innerArray.length) {
   //replace property
 } else {
   transformData()
 }
 }
}

console.log(transformData(data))
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Don't check if the array is empty, since you want to replace the property even if it's an empty array.

There's no need for the else block. There's nothing to recurse into if there's no innerArray.

The function needs to return the array so it can be assigned to the new property.

const data = [
  {name: 'First', innerArray: [{name: "InnerFirst", innerArray: []}]},
  {name: 'Second', innerArray: []}
];

function transformData(data) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].innerArray) {
      data[i].subArray = transformData(data[i].innerArray);
      delete data[i].innerArray;
    }
  }
  return data;
}

console.log(transformData(data));

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