我有一个帖子的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);
});
length
属性可用于计算JS数组中元素的数量。在这里,您有一个JS对象。因此,我们必须将其转换为其键的数组并采用length
经过
Object.keys(postNumbers).length
这是MDN文档,其中包含许多示例和有关浏览器支持的信息。
对于不支持的旧版浏览器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");
这是一个演示小提琴。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句