[英]Efficiently counting the number of keys / properties of an Object in JavaScript
[英]Counting the number of properties in a JavaScript object
所以我有這個使用arborjs顯示樹結構的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)和edge對象中的屬性數(在本例中為2),以顯示用戶樹的一些統計信息。 我通過遞歸遍歷我的數據庫並創建一個哈希來使用ruby on rails輸出數據變量。 但之前,我應該計算客戶端或服務器端的節點嗎? 我應該再次檢查數據庫並統計統計數據還是只計算屬性?
計算你可以做的節點
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.