I have a json object:
[{ "thing": "Top", "data": { "childs": [{ "thing": "a", "data": { "text": "sdfgdg1", "morestuff": { "thing": "Top", "data": { "childs": [{ "thing": "a", "data": { "text": "sdfg2", "morestuff": "", } }, { "thing": "a", "data": { "text": "gfhjfghj3", "morestuff": { "thing": "Top", "data": { "childs": [{ "thing": "a", "data": { "text": "asdfsadf 2 4", "morestuff": { "thing": "Top", "data": { "childs": [{ "thing": "a", "data": { "text": "asdfsadf 2 5", "morestuff": { "thing": "Top", "data": { "childs": { "thing": "a", "data": { "text": "asdfsadf 2 6", "morestuff": "", }, "data": { "text": "asdfsadf 2 6", "morestuff": "", } }, } }, } }], } }, } }], } }, } }], } }, } }, { "thing": "a", "data": { "text": "asdfasd1 2", "morestuff": { "thing": "Top", "data": { "childs": [{ "thing": "a", "data": { "text": "asdfsadf 2 3", "morestuff": "", } }], } }, } }, { "thing": "a", "data": { "text": "dfghfdgh 4", "morestuff": "", } }], } }]
... and I'm trying to iterate over it and get the total number of text objects.
I can't seem to get something recursive. I think I lack understanding at both json and recursion level.
After several days of options:
count=0; c2=0; c3=0; function ra(arr){ //console.log(arr.data.morestuff) if(arr!==undefined && arr.data && arr.data.morestuff===""){ c3++; }else if((arr && arr.data && typeof arr.data.morestuff==="object")){ if(arr.data.morestuff.data.childs.length>1){ for(var w=0;w<arr.data.morestuff.data.childs.length;w++){ count+=ra(arr.data.morestuff.data.childs[w]) } }else{ count+=ra(arr.data.morestuff.data.childs[0]) } } return(c3) } countn=0;//top morestuff with no morestuff tot=0; function reps(obj){ tot=obj.data.childs.length; console.log("tot="+tot) for(var x=0;x<tot;x++){ tot+=ra(obj.data.childs[x]) c3=0 if(tot>1000){//trying to prevent a runaway loop somehwere break; } } console.log(tot) } reps(json[0]);
I came to the conclusion that I simply do not know. I get different results; some of them came closer, adding together the results from the ra method, but nothing was consistent (i.e. incorrect) and always turned off by at least a few.
JSON is consistent, although there are unknown numbers of children and children, so I am looking for recursion.
Here is the fiddle: http://jsfiddle.net/CULVx/
Ideally, I would like to count every text object, its "relative position" and the number of children that I have, but I believe that I can combine this material into an array if I could just make the count work ...
NB: I tried jsonParse and other libraries to no avail. In particular, jsonParse throws an Object has no method "match" error when trying to use it on this json.