4

So I have this JavaScript literal that is displaying 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 the nodes object (3 in this case) and number of properties in the edges object (2 in this case) to display some statistics for the user tree. I output the data variable using ruby on rails by recursively going over my database and creating a hash. But before, should I count the nodes client side or server side? Should I go over the database again and count statistics or just count the properties?

Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
Nosayr Yassin
  • 419
  • 1
  • 6
  • 15
  • take a look at this: http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip – Igor Dymov Nov 22 '11 at 15:20

2 Answers2

3

to count the nodes you can do

var count=0;
for(node in data.nodes)
    count++; 
Manuel van Rijn
  • 10,170
  • 1
  • 29
  • 52
1

You could 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
Joe
  • 80,724
  • 18
  • 127
  • 145