0

I have an JSON object of posts:

{

  "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"
  }

}

the JSON object structure is:

{

  "post-id": {
    "post-url": "",
    "post-image": "",
    "post-title": ""
  }

}

I need to count number of post with jQuery length but it gives undefined error.

  $.getJSON('/all-posts.json', function(data) {
   var postNumbers = data[0];

    console.log(postNumbers.length);
  });

1 Answer 1

1

length property can be used to count the number of elements of a JS array. Here you have a JS Object. So we have to convert it into an array of its keys and take its length

by

Object.keys(postNumbers).length

Here is the MDN doc on it with lots of examples and info regarding browser support.

reply to comments

for older browsers that doesnt support Object.keys ,

you can define the function manually. like

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;
    };
}

if you want to count the number of unique urls in the 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");

Here is a demo fiddle.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks in worked, can you tell me how to count all post-urls?
sorry, I made a mistake. no need to answer. I see that this feature is for ie9+, how about olders?
Thanks for you answer, is there any way to get every inner objects like data[1], by this I mean data["how-to-create-a-blog"]. When I try with names it works but it does not work with numbers. any solutions?
You cant access because its not a js array now but a js object. But u can loop overt the object and make an array out of it. Like we did for counting the urls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.