Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To count the number of objects in object literal using Jquery

Code:

var animals = {
                    "elephant": {
                                    "name" : "Bingo",
                                    "age" : "4"
                                },
                    "Lion":     {
                                    "name" : "Tango",
                                    "age" : "8"
                                },
                    "Tiger":    {
                                    "name" : "Zango",
                                    "age" : "7"
                                }
                }

I want to count the number of objects using Jquery in this object literal.

like image 902
Programmer Avatar asked Dec 10 '12 14:12

Programmer


People also ask

How do you count object keys?

keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.

How many objects are in JavaScript?

As we know from the chapter Data types, there are eight data types in JavaScript.


1 Answers

You could use Object.keys(animals).length

Or

var count = 0;
for (var animal in animals) {
    if (animals.hasOwnProperty(animal)) {
        count++;
    }
}
// `count` now holds the number of object literals in the `animals` variable

Or one of many jQuery solutions that may or may not be the most efficient:

var count = $.map(animals, function(n, i) { return i; }).length;
like image 92
Ian Avatar answered Oct 08 '22 14:10

Ian