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.
To get the number of elements in a JavaScript object, we can use the Object. keys method. const count = Object. keys(obj).
An object. A property name of the object. A property descriptor object that has four properties: configurable , enumerable , writable , and value .
This worked for me:
Object.keys(obj).length
                        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;
}
                        I believe this has been answered on here before, and/or googling can lead you in the right direction. Nevertheless let me point out that one of the biggest gotchas if you use a loop in the form of:
for (var attr in obj) { ....
Is that the object could be cluttered with properties you did not necessarily add, and the standard solution to this as I recall is to additionally use the test for hasOwnProperty, see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With