How do I get number of fields in JavaScript object?

javascript

Solution

Old Firefox supports the `__count__` property. Newer environments support ES5's `Object.keys`. For older environments we have to fallback to just iterating over the object and counting manually (ugh!):

function count(obj) {

    if (obj.__count__ !== undefined) { // Old FF
        return obj.__count__;
    }

    if (Object.keys) { // ES5 
        return Object.keys(obj).length;
    }

    // Everything else:

    var c = 0, p;
    for (p in obj) {
        if (obj.hasOwnProperty(p)) {
            c += 1;
        }
    }

    return c;

}

Problem

I'm trying to use JavaScript object as an associative array and everything was well until I needed to get number of entries that are stored in it. What is the easiest and most elegant way to do that? All I can think of is to run `for each` loop or jQuery `$.each` function and just see how much iterations it would do but that looks like an an awful thing to do.

Original source