Barry Hamilton
Barry Hamilton

Reputation: 973

how would to count elements in keyed json in jquery

I wan't to find the number of records in a keyed json object in jquery.

For example if I have an indexed object as follows

var json = [{"key1":{"value":"33"},"key2":{"value":"36 "},"key3":{"value":"38"},"key4":{"value":"41"}}]

How could I get a count of the number of records? (their are 4 records)

Upvotes: 1

Views: 103

Answers (1)

Tushar
Tushar

Reputation: 87203

Use Object.keys() to get the array of all the keys in object.

In your case, json array contains an object. So, you can use json[0] to get the object from array and then use Object.keys() on it.

Object.keys(json[0]).length

var json = [{
  "key1": {
    "value": "33"
  },
  "key2": {
    "value": "36 "
  },
  "key3": {
    "value": "38"
  },
  "key4": {
    "value": "41"
  }
}];

document.write(Object.keys(json[0]).length);

Upvotes: 1

Related Questions