Skip to content
Advertisement

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

Advertisement

Answer

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));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement