2011-11-22 111 views
4

所以我有这个使用arborjs显示树结构的JavaScript文字。计算JavaScript对象中的属性数

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: {} 
     } 
    } 
}; 

我要计数的节点对象属性(3在这种情况下)的数目和(在这种情况2)中的边缘对象中的属性数目,以显示用户树一些统计信息。我使用ruby在rails上输出数据变量,递归地遍历我的数据库并创建一个哈希。但之前,我应该计算节点客户端还是服务器端?我是否应该再次查看数据库并统计数据或仅统计属性?

+0

看看这个:http://stackoverflow.com/questions/126100/how -to-efficient-count-the-number-of-keys-properties-of-an-object-in-javascrip –

+0

这不是JSON。 – Quentin

回答

3

计算节点,你可以做

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

这工作!非常感谢! –

1

你可以做这样的事情:

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