0

Hii have the recursion code below and while stepping through it i noticed that the value of jsonElement is not preserved well after stepping out of inner recursions. How do i go about it?

allnodes = getArrayOfNodes(tree);
function toJson(node){

    childrenList = []

    jsonElement = {}
    jsonElement["name"] = node.data


    allnodes.forEach(function(item, index){
        if(isParentOf(node, item) == true){
            allnodes.splice(index, 1)
            childrenList.push(toJson(item))
        }
    })
    jsonElement["children"] = childrenList

    return jsonElement
}
RStyle
  • 875
  • 2
  • 10
  • 29
  • Is `jsonElement` **suppose** to be a global, or was that a mistake? – Musa Nov 06 '16 at 15:52
  • wait is jsonElement actually global? Sorry i come from c# background – RStyle Nov 06 '16 at 15:53
  • How do i unglobal it. Each recursive call shud have its own jsonElement – RStyle Nov 06 '16 at 15:53
  • Looks like your jsonElement is global my friend! – WilomGfx Nov 06 '16 at 15:53
  • `var jsonElement = {}` and maybe `childrenList` shouldn't be as well. – Musa Nov 06 '16 at 15:55
  • If you want jsonElement to carry a hierarchy of nodes and its children, this is not the best way to do so ... please add your code to code snippet so we can trace it. – Doaa Magdy Nov 06 '16 at 15:56
  • Note that your `allnodes.splice(index, 1)` is mutating the `allnodes` during a forward iteration. I don't imagine that's what you want, since it would seem you'll skip over indices. –  Nov 06 '16 at 16:01

0 Answers0