Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get number of fields in JavaScript object?

Tags:

javascript

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.

like image 599
vava Avatar asked Jul 02 '09 13:07

vava


People also ask

How do you find the number of elements in an object?

To get the number of elements in a JavaScript object, we can use the Object. keys method. const count = Object. keys(obj).

How many properties are there in object?

An object. A property name of the object. A property descriptor object that has four properties: configurable , enumerable , writable , and value .


3 Answers

This worked for me:

Object.keys(obj).length
like image 70
James OB Avatar answered Oct 09 '22 23:10

James OB


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;

}
like image 24
James Avatar answered Oct 09 '22 23:10

James


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

like image 25
Dexygen Avatar answered Oct 10 '22 00:10

Dexygen