jquery - how to counts parent in an javascript object (getting not defined error) -
i trying make object number of parents of element . have array of objects .in there 2 field to , from .i want calculate length of parents here code ?
example
- "node_from": 11, don't have parent ..it don't have to field .so length 0,zero;
- "node_from": 12, coming 11 .so have parent .so parent length 1 or 1 , same in 13 , 14,16,18,19.
- "node_from": 15, has 2 parent coming 13 , 14 ..so length 2 .
can find
here code
https://jsfiddle.net/ood2ezvz/2/
var obj={} for(var i=0;i<node.length;i++){ console.log(node[i]); var node=node[i] if(obj.hasownproperty(node.node_from)){ obj[node_from]=obj[node_from]++; }else{ obj[node_from]=0; } } console.log(obj)
it giving error ?
expected out put { 11:0, 12:1, 13:1, 14:1, 15:2, 16:1, 17:1, 18:1 19:1 }
assuming "node_from" id of current node, , "node_to" children each node points to. here function can count children of each node.
var node=[ { "node_from": 11, "children": [ { "node_to": 12 } ] }, { "node_from": 12, "children": [ { "node_to": 13 }, { "node_to": 14 } ] }, { "node_from": 13, "children": [ { "node_to": 15 } ] }, { "node_from": 14, "children": [ { "node_to": 15 } ] }, { "node_from": 15, "children": [ { "node_to": 16 }, { "node_to": 17 }, { "node_to": 18 } ] }, { "node_from": 16, "children": [ ] }, { "node_from": 17, "children": [ ] }, { "node_from": 18, "children": [ { "node_to": 19 } ] }, { "node_from": 19, "children": [ ] } ]; function countparents(nodes, num){ var count = 0; for(var i=0;i<nodes.length;i++){ if(nodes[i].children){ for(var e=0;e<nodes[i].children.length;e++){ if(nodes[i].children[e].node_to == num) count++; } } } return count; } function counteachparents(nodes){ var output = []; for(var i=0;i<nodes.length;i++){ output.push( nodes[i].node_from + ":" + countparents(nodes, nodes[i].node_from) ); } return output; } document.getelementbyid( "output" ).innerhtml = counteachparents(node).join(", ");
{<span id='output'></span>}
https://jsfiddle.net/zwttlty7/
personally use oop methods handle this...
function node(id, children){ this.id = id; this.children = children || []; this.countparents = function(nodelist){ var count = 0; for(var i=0;i<nodelist.length;i++){ if(nodelist.children.indexof(this.id) > -1) count++; } return count; }; }; function nodelist(nodes){ this.list = nodes || []; this.parentcounts = function(){ var output = []; for(var i=0;i<this.list.length;i++){ var count = 0; for(var e=0;e<this.list.length;e++){ if(this.list[e].children.indexof(this.list[i].id) > -1) count++; } output.push(this.list[i].id+":"+count); } return output.join(", "); } }; var nodes = new nodelist([ new node(11, [12]), new node(12, [13,14]), new node(13, [15]), new node(14, [15]), new node(15, [16,17,18]), new node(16), new node(17), new node(18, [19]), new node(19) ]); document.getelementbyid("output").innerhtml = nodes.parentcounts();
{<span id='output'></span>}
Comments
Post a Comment