Counting the number of properties of a JavaScript object

So, I have this JavaScript literal that displays a tree structure using arborjs.

var data = { "nodes": { You: { 'color': 'green', 'shape': 'dot', 'label': 'You' }, Ben: { 'color': 'black', 'shape': 'dot', 'label': 'Ben' }, David: { 'color': 'black', 'shape': 'dot', 'label': 'David' } }, "edges": { You: { Ben: {}, David: {} }, Ben: { David: {} } } }; 

I want to count the number of properties in a node object (in this case 3) and the number of properties in an edge object (2 in this case) to display some statistics for the user tree. I infer the data variable using ruby ​​on rails, recursively navigating through my database and creating a hash. But first, should I count the nodes on the client side or on the server side? Should I browse the database again and count statistics or just read properties?

+4
source share
2 answers

to count the nodes you can execute

 var count=0; for(node in data.nodes) count++; 
+3
source

You can do something like this:

 var data = { "nodes":{ "You":{'color':'green','shape':'dot','label':'You'}, Ben:{'color':'black','shape':'dot','label':'Ben'}, David:{'color':'black','shape':'dot','label':'David'} }, "edges":{ You:{ Ben:{}, David:{} }, Ben:{ David:{}} } }; Object.prototype.NosayrCount = function () { var count = 0; for(var i in this) if (this.hasOwnProperty(i)) count++; return count; } data.NosayrCount(); // 2 data.Nodes.NosayrCount(); // 3 data.edges.NosayrCount(); // 2 
+1
source

Source: https://habr.com/ru/post/1382514/


All Articles