我有一个帖子的JSON对象:
{
"how-to-create-a-blog": {
"post-url": "blog/how-to-create-a-blog.html",
"post-image": "/posts/post-image.jpg",
"post-title": "How to create a blog"
},
"how-to-create-a-mega-menu": {
"post-url": "blog/how-to-create-a-mega-menu.html",
"post-image": "/posts/post-image.jpg",
"post-title": "How to create a mega menu"
},
"what-is-wordpress": {
"post-url": "blog/what-is-wordpress.html",
"post-image": "/posts/post-image.jpg",
"post-title": "What is WordPress"
},
"create-your-first-wordpress-theme": {
"post-url": "blog/create-your-first-wordpress-theme.html",
"post-image": "/posts/post-image.jpg",
"post-title": "Create your first wordpress theme"
}
}
JSON对象结构是:
{
"post-id": {
"post-url": "",
"post-image": "",
"post-title": ""
}
}
我需要使用jQuery length
计算帖子数,但会出现undefined
错误。
$.getJSON('/all-posts.json', function(data) {
var postNumbers = data[0];
console.log(postNumbers.length);
});
答案 0 :(得分:1)
length
属性可用于计算JS数组的元素数。这里有一个JS对象。所以我们必须将其转换为其键的数组并取其length
通过
Object.keys(postNumbers).length
以下是MDN doc,其中包含大量有关浏览器支持的示例和信息。
适用于不支持Object.keys
,
您可以手动定义该功能。像
if (!Object.keys) {
Object.keys = function (obj) {
var keys = [],
k;
for (k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
keys.push(k);
}
}
return keys;
};
}
JSON object
var uniqueURLS = [];
for (x in sample) {
if(typeof(sample[x]["post-url"]) != "undefined" && sample[x]["post-url"] != null && uniqueURLS.indexOf(sample[x]["post-url"])==-1) {
uniqueURLS.push(sample[x]["post-url"]);
}
}
alert("there were "+uniqueURLS.length+" unique urls in there");