Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda