user1847051
user1847051

Reputation:

get access to getJSON objects values

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

Upvotes: 0

Views: 66

Answers (1)

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

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.

Upvotes: 1

Related Questions