Arunesh Arunesh - 5 months ago 11
JSON Question

Can't select first value in json object

I can't seem to select the first value inside the json object.

I've tried

array[0][0]
, but it returns
undefined
.

[ { 'Room 1': 11017,
'Room 2': 2651,
'Room 3': 1,
'Room 4': 2,
'Room 5': 1,
'Room 6': 1,
'Room 7': 3,
'Room 8': 5,
'Room 9': 3661,
'Room 10': 2 } ]

Answer

Since the element is an object, it's trying to retrieve property 0 which is undefined. So you need to use the property name to get the value (eg : array[0]['Room 1']).

You can use Object.keys() to get the key array then get the value using that. But there is no guarantee of the order, since Object.keys() returns keys in an arbitrary order.

var array = [{
  'Room 1': 11017,
  'Room 2': 2651,
  'Room 3': 1,
  'Room 4': 2,
  'Room 5': 1,
  'Room 6': 1,
  'Room 7': 3,
  'Room 8': 5,
  'Room 9': 3661,
  'Room 10': 2
}]

console.log(
  array[0][Object.keys(array[0])[0]]
);