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".
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".
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++;
}
}
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