0

I have a JSON array with dynamic key value (room number, it will change every time I run the code). I'm wondering how to access inner JSON array with this key value. Here's what I have tried and it throws an error.

JSON Array(data)

[{"6011":
 [{"occupancy":"2","time":"2017-11-10 00:00:00"},
 {"occupancy":"1","time":"2017-11-10 00:30:00"},
 {"occupancy":"2","time":"2017-11-10 01:00:00"}]
}]

Code to access

var room = outerJSON.name;

var jsonObject = jQuery.parseJSON(JSON.stringify(data));

var innerArray = jsonObject[room]; // returns undefined
var innerArray2 = jsonObject.get(room); // Uncaught TypeError: jsonObject.get is not a function
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
ejshin1
  • 1,107
  • 6
  • 17
  • 35

2 Answers2

2

Your object are inside an array, so you should point your code to the first column of the array jsonObject using [0] like :

var innerArray = jsonObject[0][room];

var data = [{
  "6011": [{
      "occupancy": "2",
      "time": "2017-11-10 00:00:00"
    },
    {
      "occupancy": "1",
      "time": "2017-11-10 00:30:00"
    },
    {
      "occupancy": "2",
      "time": "2017-11-10 01:00:00"
    }
  ]
}];

var room = "6011";
var jsonObject = jQuery.parseJSON(JSON.stringify(data));
var innerArray = jsonObject[0][room];

console.log(innerArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
halfer
  • 19,824
  • 17
  • 99
  • 186
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

Assuming room has the value 6011 or "6011", and assuming {"6011":} is not always the only object in the array, you need to find that object first, since your object is wrapped in an array. You can then access the room property by [room].

var jsonObject = [{ "6011": [{ "occupancy": "2", "time": "2017-11-10 00:00:00" }, { "occupancy": "1", "time": "2017-11-10 00:30:00" }, { "occupancy": "2", "time": "2017-11-10 01:00:00" } ] }, { "6012": [{ "occupancy": "2", "time": "2017-11-10 00:00:00" }, { "occupancy": "1", "time": "2017-11-10 00:30:00" }, { "occupancy": "2", "time": "2017-11-10 01:00:00" } ] }],
  room = 6011;

var foundObject = jsonObject.find(obj => obj.hasOwnProperty(room));

console.log(foundObject && foundObject[room]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75