javascript - Traverse a json object recursively Results in "uncaught syntaxError: Illegal return statement" -
i'm trying navigate through json object first time recursively, , code when running through debugger appears work until tries return object when have found groupid looking for. error getting:
uncaught syntaxerror: illegal return statement @ object.injectedscript._evaluateon (<anonymous>:895:55) @ object.injectedscript._evaluateandwrap (<anonymous>:828:34) @ object.injectedscript.evaluateoncallframe (<anonymous>:954:21) @ findgroupid (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:503:21) @ findgroupid (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32) @ findgroupid (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32) @ findgroupid (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32) @ findgroupid (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32) @ findgroupid (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32) @ findgroupid (http://s.codepen.io/boomerang/5978872e6c1baaa184d2e8ced60239201437139491273/index.html?editors=001:491:32) feel free critique part of first time trying this. :)
my sample code following:
'use strict'; var findgroupid = function (obj, id) { var checkforid = function (key, obj) { if (key == id) { return true; } return false; }; if (typeof obj === 'object') { (var in obj) { if (typeof obj[i] === 'object') { findgroupid(obj[i], id); } else if (array.isarray(obj[i])) { (var x = 0 ; x <= obj[i].length ; x++) { findgroupid(obj[i], id); } } else { var result = checkforid(obj[i], obj); if (result) { debugger; return obj; } } } } }; var result = findgroupid(obj, "37078;1"); console.log(result); here executable example: http://codepen.io/eaglejs/pen/voazgd
here fixed solution pablo: http://codepen.io/eaglejs/pen/qbbkgk
the issue here arent returning anything, have return function calls in code.
the easiest fix store result , return if not undefined.
function checkforid(key, obj, id) { if (key == id) { return true; } return false; } var findgroupid = function (obj, id) { if (typeof obj === 'object') { (var in obj) { if (typeof obj[i] === 'object') { var myresult = findgroupid(obj[i], id); if (myresult) return myresult; } else if (array.isarray(obj[i])) { (var x = 0; x <= obj[i].length; x++) { var myresult = findgroupid(obj[i], id); if (myresult) return myresult; } } else { var result = checkforid(obj[i], obj, id); if (result) { return obj; } } } } }; modified codepen works
note improved little findgroupid removing checkforid , putting outside of "loop" because otherwise redefine on , on again.
Comments
Post a Comment