Looking to extract specific data from my JSON response with the following structure;
{
"status": "success",
"reservations": [
{
"id": "26630",
"subject": "Subject",
"modifiedDate": "2017-05-16T06:05:12",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T09:45:00",
"resources": [
{
"id": "2408",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3020",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "48",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildngName"
},
"name": "RoomName (PC)"
}
],
"description": ""
},
{
"id": "21173",
"subject": "subjectName",
"modifiedDate": "2017-05-16T06:05:20",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T16:00:00",
"resources": [
{
"id": "3115",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "2584",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "52",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildingName"
},
"name": "roomName (classroom)"
}
],
"description": ""
}
]
}
After parsing it as an object using JSON.parse()
and looping through it using for-loops
:
var json = JSON.parse(data.responseText);
for (var i = 0; i < json.reservations.length; i++) {
if (json.reservations[i].resources != null) {
for (var j = 0; j < json.reservations[i].resources.length; j++) {
var reservations = json.reservations[i];
var resources = json.reservations[i].resources[j];
}
}
}
The task is to extract the room names before the key name "description"
:
"name": "roomName (PC)"
"name": "roomName (classroom)"
While I've kept the example JSON response short, in reality there are multiple room names. The goal is to retrieve all room names from the JSON response body, add them into an array, and display them chronologically like so;
roomName (PC)
roomName (classroom)
I'm seeking a fast and efficient method to achieve this.