views:

28

answers:

1

Hi,

I am here to ask a nested array question. I have a file say, "content.json" which has javascript variables and json as their values in json there are objects as value and objects as value of each object. I mean there is deep chain to overcome to reach the final value and it is not already decided how many elements at the root are and how many elements at any stage are.

What type of looping I must consider to show the results in some format as <pre></pre> block does?

I am avoiding recursion because of memory issues so looping should be implemented.

Thanks

+1  A: 

Avoiding recursion for memory issues is a mistake, basically. Consider a deeply nested object like

var obj = {{{{{{{{{thing: 0}}}}}}}}}

In pseudocode, you can examine this to any depth by using

getThing(obj)
if obj == nul return
if obj.thing is defined you're at the bottom
// otherwise
getThing(obj[0])

for each recursion, all the memory you use is a stack frame: a return address and a pointer, basically. In this case, about 18 words of memory.

What you're doing is essentially a tree; you only need about lg depth memory to recursively explore a tree depth first; if you prefer, lg number of items/2 additional memory. (Pop quiz: why is this true?)

Charlie Martin
you are right but how about to get to top to move into an other hole?
Umair Ashraf
Umair, you should look into a data structures book. I don't know what the good ones are any longer, it having been 20+ years since grad school, but there's always Knuth, tho' it can be tough going.Basically, though, you can keep a pointer to the top of the tree in a global, and find the new spot that way.Start with this wiki article and see if that help: http://en.wikipedia.org/wiki/Binary_search_tree
Charlie Martin