1

How can you get the length of this kind of array using javascript or jquery?

var Accounts = {
'Account001' : { 'data1' : 'foo1', 'data2' : 'bar1' },
'Account002' : { 'data1' : 'foo2', 'data2' : 'bar2' },
'Account003' : { 'data1' : 'foo3', 'data2' : 'bar3' },
'Account004' : { 'data1' : 'foo4', 'data2' : 'bar4' }
};

I tried Accounts.length but it seems to return NAN.

zeddex
  • 1,260
  • 5
  • 21
  • 38

2 Answers2

10
Object.keys(Accounts).length

You are trying to get the "length" of an object, which does not exist. If this were an array, it would be enclosed in a bracket [].

This is definitely an object, so in order to count the properties inside an object, you would have to use Object.keys() to contain the property names in an array and then count the elements from there.

Vic
  • 703
  • 6
  • 9
2

You can use a for loop to iterate over all the elements in the object and a count to get the number:

var Accounts = {
'Account001' : { 'data1' : 'foo1', 'data2' : 'bar1' },
'Account002' : { 'data1' : 'foo2', 'data2' : 'bar2' },
'Account003' : { 'data1' : 'foo3', 'data2' : 'bar3' },
'Account004' : { 'data1' : 'foo4', 'data2' : 'bar4' }
};

var count = 0;
for(var k in Accounts) {
  if(Accounts.hasOwnProperty(k)) {
    count++;
  }
}
console.log(count);
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69