views:

485

answers:

2

I have a custom object which contains other items (ie arrays, strings, other types of objects).

I am not sure how to traverse the object to iterate and list all of the object types, keys, and values of the nested items.

Second to this issue I don't know how many levels of nesting there are (as the object is generated dynamically from the back-end and passed to me as one object).

Any ideas (and should I just use javascript/jQuery or both to do this most efficiently)?

+2  A: 

JSON-serialized objects contain a hierarchy, w/o any reference cycles, so it should be fairly straightforward to traverse, something like

function visit(JSONobj, f)
{ 
   for (var key in JSONobj)
   {
       var value = JSONobj[key];
       f(key,value);
       if (value instanceof Object)
           visit(value, f);
   }
}

where f is a function that does something with keys and values. (of course you could just write a function to do this directly).

What exactly are you trying to find within the object?

Jason S
A: 

Thanks I'll give the code a go. I am retrieving a result set from a webservice which returns a different set of columns (of differing datatypes) and rows each time. I don't know the names of the columns which is why I am trying to get the data however I can.

Depending on the datatype I will perform a different action (sum the amount, format it etc).