Skip to content
Advertisement

Create a nested array recursively in Node.js

Following is my array

JavaScript

and I want to have objects nested like this as output :

JavaScript

Please help me with a recursive function to do this in node.js.

Following is the recursive function is what I have tried:

JavaScript

Please help me to solve this. I am a newbie in this.

Advertisement

Answer

Renaming some variables helped me solve this.

  • getNestedChildren returns an array of children, so rename out to children.
  • the children returned by the recursive call are the grandchildren of the parent being processed in the call. So call the result of the recursive call grandchildren.

The problem that caused the code to not work:

  • line 4 of the posted code uses the id property of the parent parameter. So either ensure that every call to getNestedChidren provides an object with such a property (as below), or change the second argument to parentNumber and just supply the numeric value of the number property. Your choice.

Lastly, avoid using for ... in loops to iterate an array – please do a web search for more information and discussion.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement