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

95
Views
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 answers
Answer question

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