0

I've a hierarchical json object, I want to traverse it and attach a parent node to each element. This is what I've done

function attach_back_reference(hierarchy, parent){
    hierarchy.parent = parent;
    for(var i in hierarchy){
        if(jQuery.isPlainObject(hierarchy[i]))
            attach_back_reference(hierarchy[i], hierarchy);
    }
}

But this is giving error. Maximum call stack size exceeded

Dipro Sen
  • 4,350
  • 13
  • 37
  • 50

2 Answers2

1

Since you do

for(var i in hierarchy){

after adding the parent property, one value of i will be "parent", so you end up setting the child as its own grandparent infinitely.

You can see this in

var o = {};
o.x = o;
for (var i in o) { alert(i); }

which alerts "x".

Move the loop to the top.

function attach_back_reference(hierarchy, parent){
    for(var i in hierarchy){
        if(jQuery.isPlainObject(hierarchy[i]))
            attach_back_reference(hierarchy[i], hierarchy);
    }
    hierarchy.parent = parent;
}

Alternatively, if you only need this to work on newer interpreters, you can try making the parent property unenumerable : javascript defineProperty to make an attribute non enumerable

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • Thanks. I overlooked that. also I found that It doesn't work if I've an array in the middle of hierarchy – Dipro Sen Dec 24 '12 at 19:26
  • also can you tell me how to handle arrays ? so that it assigns parent to first object(non-array) ancestor ? – Dipro Sen Dec 24 '12 at 19:29
0

You have an infinite loop there.

You are setting the parent of each object as itself.

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • But I am passing `attach_back_reference(hierarchy[i], hierarchy)` so `hierarchy[i].parent = hierarchy` will be executed – Dipro Sen Dec 24 '12 at 19:22