0

My Code:

$.post("@(Url.Action("SelectAction", "ControllerName"))", function(data){
    // How to get the count of the data(object)
});

How to get the count of the data(object). I used data.count but is returning as "undefined".

Asif Mushtaq
  • 12,420
  • 2
  • 31
  • 42
  • Is it an object, or is it in fact a string or array ? – adeneo Nov 05 '12 at 10:50
  • Are you sure a value is being passed by data? – ianaldo21 Nov 05 '12 at 10:52
  • `Object.keys(data).length` in newer browsers should work. Otherwise you'll have to iterate the object as length is'nt supported for objects. See this [SO answer](http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip) ? – adeneo Nov 05 '12 at 10:52

2 Answers2

0

If you want to count the no. of properties in an object, you could use:

Object.keys(data).length

Or if you want a cross-browser approach, you'll need to loop through the object itself using:

var count = 0;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        count++;
    }
}
kayen
  • 4,554
  • 3
  • 17
  • 20
0

Use Object.keys as pointed out in other answers (Object.keys(data).length).

Don't use a temporary fix if you want cross-browser compatibility however. Use a shim. It's simple enough and will just be better for newer browsers. Old browsers will simply use the shim.

Quick shim:

if (!Object.keys) Object.keys = function(o) {
  if (o !== Object(o))
    throw new TypeError('Object.keys called on a non-object');
  var k=[],p;
  for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
  return k;
}

Source: http://tokenposts.blogspot.com.au/2012/04/javascript-objectkeys-browser.html

Florian Margaine
  • 50,873
  • 14
  • 87
  • 110