计算JavaScript对象中属性的数量

Counting the number of properties in a JavaScript object

本文关键字:属性 JavaScript 对象 计算      更新时间:2023-09-26

所以我有这个JavaScript文字,它使用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: {}
        }
    }
};

我想计算nodes对象(本例中为3个)和edges对象(本例中为2个)中的属性数量,以显示用户树的一些统计信息。我使用ruby on rails通过递归遍历数据库并创建散列来输出data变量。但在此之前,我应该计算客户端还是服务器端节点呢?我应该再检查一遍数据库,计算统计数据还是只计算属性?

计算节点个数

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

你可以这样做:

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