0

Continuied from json back reference.

I just want to travarse a hierarchy and set a property parent to its parent node. so that its both way travarsable

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

The above function works well in chrome, opera, firefox, IE9 . except IE 8 where it says Out of stack space. But I don't see anywhere it goes towards infinite recursion

Community
  • 1
  • 1
Dipro Sen
  • 4,350
  • 13
  • 37
  • 50
  • Just in case you have some sort of loop in your tree, I'd suggest adding if(hierarchy.parent)return; at the top of the function. – Dave Mar 07 '13 at 20:06

2 Answers2

0

As per this answer IE8 has a much smaller stack limit than other browsers, so I guess your javascript might actually be reaching the limits of IE8.

Community
  • 1
  • 1
igoratron
  • 134
  • 3
0

Here's a version of your code which doesn't use recursion, so won't suffer from this:

function attach_back_reference( hierarchy, parent ) {
    var q = [{obj:hierarchy, p:parent}];
    while( q.length ) {
        var o = q.pop( ), x = o.obj;
        if( x.parent ) {
            continue;
        }
        for( var i in x ) {
            if( jQuery.isPlainObject( x[i] ) ) {
                q.push( {obj:x[i], p: x} );
            } else if( jQuery.isArray( x[i] ) ) {
                for( var j in x[i] ) {
                    q.push( {obj:x[i][j], p: x} );
                }
            }
        }
        o.p && (x.parent = o.p);
    }
}

(it also won't hang if given a graph with loops, but that's still not a good idea)

Dave
  • 44,275
  • 12
  • 65
  • 105