tags:

views:

41

answers:

2

In Javascript how can I get the full ancestral hierarchy in a string given just a single object? Right now I can't even think about how to ask the question... so I can't even google it. Here's an example:

var lvl1 = { one: "one", two: "two" };
lvl1.lvl2 = {flip:"flip", flam:"flam"};
lvl1.lvl2.lvl3 = {who:"who", what:"what"};

test(o) {
     alert( hierarchyToString(o) );
}

var tmp = lvl1.lvl2.lvl3;
test(tmp);

I want to see:

"lvl1.lvl2.lvl3"

possible? what if I passed in the final leaf string:

test(lvl1.lvl2.lvl3.what);

possible? hopefully that code makes sense... just off top of my head...

Thank you!

+1  A: 

Not possible using plain JavaScript objects as there are no parent references. See this question for more details.

Unfortunately it's easy to go from the string representation to the object, but not the other way around. You will have to explicitly code the parent references in each object, and each leaf node to be able to traverse upwards.

Anurag
thanks Anurag... i'm obviously brain-dead today (haven't slept in several)... of course an object could be referenced by many other objects, and thus you can't expect it to have a single parent, which renders my question dumb :)
Nick Franceschina
A: 

You could do something like this, but it can not identify the name of the root element..

var lvl1 = { one: "one", two: "two" };
lvl1.lvl2 = {flip:"flip", flam:"flam"};
lvl1.lvl2.lvl3 = {who:"who", what:"what"};

function test(o) {
     for (var item in o)
     {
         if (typeof( o[item] ) === 'object')
         {
             var next = test( o[item] );
             if (next != '')
                 return item + '.' + next
             else
                 return item ;
         }
     }
     return '';
}
alert( test( lvl1 ) );

And it can only go outer->inner not the other way arround..

To identify the first element, you could use an empty parent node..

var root={};
root.lvl1 = { one: "one", two: "two" };
root.lvl1.lvl2 = {flip:"flip", flam:"flam"};
root.lvl1.lvl2.lvl3 = {who:"who", what:"what"};

and call it with alert( test( root ) );

Gaby