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.
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.
As we know from the chapter Data types, there are eight data types in JavaScript.
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;
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