[英]Identifying the last item in a JavaScript object or associative array
我正在整理一些JavaScript,這些JavaScript將提取多個JSON文件,其數據將在圖形中使用。 最終,我需要確定何時到達$.each()
循環(涉及jQuery)中正在處理的關聯數組的絕對末尾,以觸發下一個JSON文件。 我碰到了一個單層對象的各種解決方案...但是多層對象呢? 最后一列的最后一行如何得知是LAST?
這是我正在使用的示例JSON:
{
"Network":{
"Hardware":262464,
"Software":53016,
"Internal Personnel":440202,
"External Personnel":188658,
"Outside Services":1344100,
"Facilities and Overhead":16172,
"Other":92588,
"Total":2397200
},
"Wide Area Network":{
"Hardware":75600,
"Software":18900,
"Internal Personnel":132300,
"External Personnel":56700,
"Outside Services":315000,
"Facilities and Overhead":6300,
"Other":25200,
"Total":630000
}
}
這是我在JSON上運行的循環的粗略概念
function buildColumns(array, parent) {
$.each(array, function(key, value) {
var newParent = $('<column>');
$('<columnBox>').append($('<h2>').html(key)).append(newParent).appendTo(parent);
if(value instanceof Object) buildColumns(value, newParent);
});
}
如您所見,該循環是偽遞歸的,並且最終可能不是我所使用的。 但是,你去了。
您可以使用length
屬性找出數組中有多少個項目。
因此,在您的示例中array.length
將返回項目數。 假設傳遞的變量是一個數組。
對對象執行此操作的方法是:
Object.keys(jsonObject).length
另外,由於我不確定是要查找長度的數組還是對象,因此可以使用下面的代碼向對象添加一個count
方法,以查找該對象具有多少個子代:
Object.prototype.count = function() {
oCount = 0;
for(var curObj in this)
if(curObj.hasOwnProperty(prop)) oCount++;
return oCount;
};
照這樣使用:
console.log(jsonObject.count());
JavaScript對象的字段順序不能保證一致。 既不隨着時間的推移,也不在不同的瀏覽器之間。 請參閱此處: JavaScript是否保證對象屬性順序?
因此,最后一項並不總是相同的。
如果要獲得最后一項,則需要將對象重新加工為數組。
{
"Network": [
[{"Hardware":262464}],
[{"Software":53016}],
// ...
],
"Wide Area Network":[
[{ "Hardware":75600}],
// ...
],
// ...
}
他
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.