javascript - recursive callback over set of nodes -
i have tree structure (jstree.js ) list of dom elements. each element check if parent, select children, , check there parent status, ...
i need parse tree elements array of objects. if element parent, given additional property, array of child object. child objects checked recursively.
here basic structure trying parse list of dom elements into. this output looking for
[ {s:0,c:[ {s:1}, {s:2,c:[s:3]}, {s:4} ]} ]
here basic recursive function: check type()
of node. if parent trying use callback recurse on set of children. if child element, return id attribute
function parse3(rootelem,obj,freduce) { function type(e){ //var e = new element(root.id) // return !e.isparent ? {'sibling':e.jstxt} : freduce( parent, cb) if (!e.isparent){ console.log('- - - child - - -', e.jstxt ) return {'sibling':e.jstxt} } if (e.isparent) { console.log('- - - parent - - -', e.jstxt ) return freduce(obj, e, function(i){ ( var i=0; i<e.numchildren; i++ ){ console.log('recurse',i ,' ', type( e.childelements[i]) ); type( e.childelement[i] ) }}) } }//close type return type(rootelem) }//parse3
next, (i got work primitive types) since dealing methods return reduce function holds cb.
function freduce(obj, e,cb){ obj.push( {'sibling':e.jstxt, 'xml':[] } ) var obl= obj.length-1 == undefined ? 0 : obj.length-1 obj[ obl ].xml.push( cb ) return obj }
how iterate on selected childnodes. little new javascript , not sure callback logic using iterate on children. further, unsure how reduce child property element object.
(in dealing nested structure, able work primitives (numbers). dealing objects , iterating on set of child elements causing problems ...)
any suggestion appreciated!
you don't need call freduce
complicates things. can create xml
property inside type function without whole call , callback pattern.
also, should try not pass obj
around: instead build recursive return value, final return value: way caller gets result:
function parse3(rootelem) { function type(e){ var obj = {'sibling': e.jstxt}; if (e.isparent){ obj.xml = []; (var i=0; i<e.numchildren; i++ ){ obj.xml.push(type(e.childelement[i])); } } return obj; } return type(rootelem); }
nb: should better not name variables capitals, commonly used denote constant primitive values. first letter should not capitalised, used constructor/class names.
some further improvements:
with above code, function parse3
in essence not different more function type
: both take same arguments , return same kind of information.
furthermore, can iterate on childelement
list map
function, or (if not real array), array.from
callback. becomes nice in 1 expression, making use of object.assign
:
function parse3(e) { return object.assign ({sibling: e.jstxt}, e.isparent ? { xml: array.from(e.childelement, parse3) } : {}); }
Comments
Post a Comment