0

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))
1
  • 1
    What is InnerFirst? Is that supposed to be a string? Commented Sep 20, 2021 at 21:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.