javascript - Recursive Function not working correctly -
i have recusive function supposed loop through json object , output expression. however, recusion seems off because it's outputting field1 != '' , field3 == '' when should outputting field1 != '' , field2 == '' , field3 == ''
i've tried couple different things , way can work creating global variable outstring
instead of passing function. off? when step through it, see correct result once stack reverses, start resetting outstring
, stack again leaves out middle (field2).
function buildstring(json, outstring) { var andor = json.condition; (var rule in json.rules) { if (json.rules[rule].hasownproperty("condition")) { buildstring(json.rules[rule], outstring); } else { var field = json.rules[rule].id; var operator = json.rules[rule].operator; var value = json.rules[rule].value == null ? '' : json.rules[rule].value; outstring += field + ' ' + operator + ' ' + value; if (rule < json.rules.length - 1) { outstring += ' ' + andor + ' '; } } } return outstring; } var jsonobj = {"condition":"and","rules":[{"id":"field1","operator":"!= ''","value":null},{"condition":"and","rules":[{"id":"field2","operator":"== ''","value":null}]},{"id":"field3","operator":"== ''","value":null}]}; $('#mydiv').text(buildstring(jsonobj, ""));
the function has return of string.
when call function recursively within itself, aren't doing returned string instance, calling function has return to
change:
if (json.rules[rule].hasownproperty("condition")) { buildstring(json.rules[rule], outstring); }
to
if (json.rules[rule].hasownproperty("condition")) { // include returned value in concatenated string outstring += buildstring(json.rules[rule], outstring); }
Comments
Post a Comment