114

Possible Duplicate:
Length of Javascript Object (ie. Associative Array)

I have an object similar to this one:

var jsonArray = {
  '-1': {
    '-1': 'b',
    '2': 'a',
    '10': 'c'
  },
  '2': {
    '-1': 'a',
    '2': 'b',
    '10': 'a'
  },
  '5': {
    '-1': 'a',
    '2': 'a',
    '10': 'b'
  }
};

I'm trying to get it's length, the problem is that jsonArray.length returns 5 instead of 3 (which is the total items it has). The array is relatively long (has 1000x2000 items) and this must be done a lot of times every second. How can I get the number of items more efficiently?

2
  • 7
    jsonArray isn't an array. Commented Dec 8, 2012 at 22:46
  • 2
    Object.keys(jsonArray).length; an object does'nt have a length property, and your object is neither an array nor valid json. Commented Dec 8, 2012 at 22:50

3 Answers 3

183

In addition to kieran's answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:

Object.keys(jsonArray).length;

More details in this answer on How to list the properties of a javascript object

Sign up to request clarification or add additional context in comments.

2 Comments

why do you write Object.keys(...) and not just keys(), It works both ways, what is the difference between those two ???
Chrome v54 doe not have this.
22

That's an Object and you want to count the properties of it.

Object.keys(jsonArray).length

References:

Comments

6

Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length returns undefined rather than 5.

This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.