Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total number of items on Json object? [duplicate]

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?

like image 353
lisovaccaro Avatar asked Dec 08 '12 22:12

lisovaccaro


People also ask

How do you find the number of elements in a JSON array?

You can get the number of elements in an array using yourArray. length .

Can you do calculations in JSON?

No, it isn't possible to do math or any kind of expression in JSON as JSON is just a data structure format, and not a programming language.

How many JSON objects are represented?

JSON Syntax JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.


2 Answers

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

like image 104
NT3RP Avatar answered Sep 28 '22 19:09

NT3RP


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

Object.keys(jsonArray).length 

References:

  • Object.keys.
  • Kangax's compat table.
like image 25
Alexander Avatar answered Sep 28 '22 19:09

Alexander