Search code examples
javascriptrecursionmultidimensional-arraynested-loops

nesting parent-child using recursion


I have json object like this

[
{"id" : 1, "parentid" : null},
{"id" : 2, "parentid" : null},
{"id" : 3, "parentid" : 2},
{"id" : 4, "parentid" : 3}
]

I want to make it nested like this in javascript

[
{"id" : 1, "parentid" : null},
{"id" : 2, "parentid" : null, "childs": 
   [{"id" : 3, "parentid" : 2, "childs": 
     [{"id": 4, "parentid" : 3}]}]
}
]

Do I need to use recursion function or just a simple loop will do it? What is the most efficient way to achieve it?


Solution

  • You have to use recursive function for this. Simple loop will not work, because there can be n number of objects in an array and upto n level. Here is a function that you can utilize

    var a = [{
        "id": 1,
        "parentid": null
      },
      {
        "id": 2,
        "parentid": null
      },
      {
        "id": 3,
        "parentid": 2
      },
      {
        "id": 4,
        "parentid": 3
      }
    ]
    
    
    function getNestedChildren(arr, parent) {
        var out = []
        for(var i in arr) {
            if(arr[i].parentid == parent) {
                var children = getNestedChildren(arr, arr[i].id)
    
                if(children.length) {
                    arr[i].children = children
                }
                out.push(arr[i])
            }
        }
        return out
    }
    
    console.log(getNestedChildren(a))

    Link: http://oskarhane.com/create-a-nested-array-recursively-in-javascript/