I am trying to sort through some data regarding seat vacancies using nodejs. The response from the API is like this
{
"data":[
{
"date":"2016-10-01",
"timeslots":[
{
"from_time":"10:00",
"to_time":"18:00",
"vacancies":2400
},
{
"from_time":"18:00",
"to_time":"21:00",
"vacancies":900
}
]
},
{
"date":"2016-10-02",
"timeslots":[
{
"from_time":"10:00",
"to_time":"18:00",
"vacancies":2400
},
{
"from_time":"18:00",
"to_time":"21:00",
"vacancies":900
}
]
},
{
"date":"2016-10-03",
"timeslots":[
{
"from_time":"10:00",
"to_time":"18:00",
"vacancies":2400
},
{
"from_time":"18:00",
"to_time":"21:00",
"vacancies":900
}
]
},
{
"date":"2016-10-04",
"timeslots":[
{
"from_time":"10:00",
"to_time":"18:00",
"vacancies":2400
},
{
"from_time":"18:00",
"to_time":"21:00",
"vacancies":900
}
]
},
{
"date":"2016-10-05",
"timeslots":[
{
"from_time":"10:00",
"to_time":"18:00",
"vacancies":2400
},
{
"from_time":"18:00",
"to_time":"21:00",
"vacancies":900
}
]
}
]
}
And I am trying to process this using the code below
app.get('/fetchdata/:ticketid/:fromdate/:todate', function (req, res){
var id = req.params.ticketid;
var fromdate = req.params.fromdate;
var todate = req.params.fromdate;
var key = id+fromdate+todate;
var username = 'foo';
var password = 'foobar';
var slot_url = "https://"+username+":"+password+"@boo.boobar.com/1/timeslots?productId="+id+"&fromDate="+fromdate+"&toDate="+todate;
var result = {};
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
request({
url: slot_url,
json: true,
headers: headers
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var data = [];
try {
body.forEach(function (entry) {
var temp = {};
temp['date'] = entry["date"];
data = data.concat(temp);
});
result['data'] = data;
result['response'] = 1;
result['message'] = 'Capacity list fetched successfully!';
//client.set(key, JSON.stringify(data));
res.json(result);
}
catch (err) {
result['response'] = 0;
result['message'] = 'No data found!';
result['exception'] = err.message;
res.json(result);
}
}
else
{
console.log("Something went wrong!! "+error.message);
}
})
});
Now I keep getting the response {"response":0,"message":"No data found!","exception":"Object #<Object> has no method 'forEach'"}
I understand that this is because the timeslots key inside the data key is an object but I am unable to parse this. What changes should be done to my code to be able to parse this content.
My ultimate objective is to sort out this data according to the dates and create a json like this
{
"2016-10-01":[
{
"from_time":"10:00",
"to_time":"10:30",
"capacity":-147
},
{
"from_time":"10:30",
"to_time":"11:00",
"capacity":1
}
]
}