12

I have json object which is returned from php file, the json values are as follows

    {
  "0": {
    "id": "35",
    "name": "first name",
    "date": "2014-03-03",
    "age": "25"
  },
  "1": {
    "id": "36",
    "name": "name",
    "date": "0000-00-00",
    "age": "25"
  },
  "2": {
    "id": "37",
    "name": "myname",
    "date": "0000-00-00",
    "age": "25"
  },
  "average_age": 25,
  "count": 3
}

How do I get the count of values other than average_age and count that is for the given json object i want to get 3 as length in jQuery

droidev
  • 7,352
  • 11
  • 62
  • 94

4 Answers4

57

I have got the answer

Object.keys(result).length // returns 5

UPDATE

From the comment this does not work on IE 7 and 8

droidev
  • 7,352
  • 11
  • 62
  • 94
  • As it's important to my case: just note that this does not work IE8 and lower as per http://stackoverflow.com/a/14379528/731782 – DavidP Jul 18 '14 at 10:22
8

Try:

var count = 0;
while (obj[count]) {
    count++;
}
John S
  • 21,212
  • 8
  • 46
  • 56
1

To "get the count of values other than average_age and count", you can do something like this:

function getCount(obj) {
    var count = 0,
        prop;

    for (prop in obj) {
        if (obj.hasOwnProperty(prop) && prop !== "average_age" && prop !== "count") {
            count += 1;
        }
    }
    return count;
}

var str = '{"0":{"id":"35","name":"Ahamed shajeer","date":"2014-03-03","age":"25"},"1":{"id":"36","name":"Meshajeer","date":"0000-00-00","age":"25"},"2":{"id":"37","name":"Iam shajeer","date":"0000-00-00","age":"25"},"average_age":25,"count":3}',
    obj = JSON.parse(str);

console.clear;
console.log(getCount(obj));

Result:

3

You don't need jQuery. Anyway, why don't you want to use the count field directly?

kol
  • 27,881
  • 12
  • 83
  • 120
0

This way worked for me:

var jsonObject= JSON.stringify(response); var count = JSON.parse(jsonObject).length;