javascript - looping through an object (tree) recursively -
is there way (in jquery or javascript) loop through each object , it's children , grandchildren , on?
if so... can read name?
example:
foo :{ bar:'', child:{ grand:{ greatgrand: { //and on } } } }
so loop should this...
loop start if(nameof == 'child'){ //do } if(nameof == 'bar'){ //do } if(nameof =='grand'){ //do } loop end
you're looking for...in
loop:
for (var key in foo) { if (key == "child") // something... }
be aware for...in
loops iterate on enumerable properties, including added prototype of object. avoid acting on these properties, can use hasownproperty
method check see if property belongs object:
for (var key in foo) { if (!foo.hasownproperty(key)) continue; // skip property if (key == "child") // something... }
performing loop recursively can simple writing recursive function:
// function handles arrays , objects function eachrecursive(obj) { (var k in obj) { if (typeof obj[k] == "object" && obj[k] !== null) eachrecursive(obj[k]); else // something... } }
Comments
Post a Comment