EN
JavaScript - how to get length of associative array?
1 answers
0 points
How can I get the length of an associative array in JavaScript?
I have an associative array (or as some say - an object) like this:
xxxxxxxxxx
1
var items = new Array();
2
3
items['a1'] = 'item 1';
4
items['a2'] = 'item 2';
5
items['a3'] = 'item 3';
Is there any built-in function that could get the length of this array without iterating it?
I tried items.length
but returns 0
.
1 answer
0 points
There is no built-in method that returns the number of properties the object has.
However, you can use Object.keys()
method to get an array of property names and then get the length
of it like this:
xxxxxxxxxx
1
var items = new Array();
2
3
items['a1'] = 'item 1';
4
items['a2'] = 'item 2';
5
items['a3'] = 'item 3';
6
7
console.log(Object.keys(items).length); // 3
Note:
Object.keys()
returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.xxxxxxxxxx
1console.log(Object.keys(items)); // Output: [ 'a1', 'a2', 'a3' ]
References
0 commentsShow commentsAdd comment