I have created a get route for a page which displays user info. In this I have created a list array which I have passed to render object and this list contains 2 things one is user image which is displaying correctly and the other is his attendance in form of an array which includes different objects.
The problem is when I am pushing this objects they are not getting added to the dates array and are not getting displayed in the list array. Also when I am console logging the objects they are getting displayed individually.
router.get("/me", ensureAuthenticated, async (req, res) => {
var empCode = req.user.empCode;
var list = []
list.photo = await Document.findOne({
empCode: empCode
}).then(employee => {
return employee.photo;
});
list.attendance = await Attendance.findOne({
empCode: empCode
}).then(employee => {
var dates = [];
var emp = {};
employee.years.forEach(year => {
yearName = year.name;
emp["year"] = yearName;
year.months.forEach(month => {
monthName = month.name;
emp["month"] = monthName;
month.days.forEach(day => {
date = day.date;
inTime = day.inTime;
outTime = day.outTime;
status = day.status;
emp["date"] = date;
emp["inTime"] = inTime;
emp["outTime"] = outTime;
emp["status"] = status;
dates.push(emp); // Here is i console log the objects are getting displayed.
});
});
});
return dates;
});
console.log(list);
res.render("me", {
user: req.user,
list
});
});
If I console.log(emp); in forEach loop this is the result.
{
year: '2020',
month: 'Jan',
date: '1',
inTime: '09:40',
outTime: '18:10',
status: 'On Time'
}
{
year: '2020',
month: 'Feb',
date: '3',
inTime: '10:15',
outTime: '18:15',
status: 'Late'
}
{
year: '2020',
month: 'Feb',
date: '4',
inTime: '10:20',
outTime: '18:20',
status: 'Late'
}
[ photo: '', attendance: [] ]
But if I do dates.push(emp); then I get.
[
photo: '',
attendance: [
{
year: '2020',
month: 'Feb',
date: '4',
inTime: '10:20',
outTime: '18:20',
status: 'Late'
},
{
year: '2020',
month: 'Feb',
date: '4',
inTime: '10:20',
outTime: '18:20',
status: 'Late'
},
{
year: '2020',
month: 'Feb',
date: '4',
inTime: '10:20',
outTime: '18:20',
status: 'Late'
}
]
]
And what I want is this.
[
photo: '',
attendance: [
{
year: '2020',
month: 'Jan',
date: '1',
inTime: '09:40',
outTime: '18:10',
status: 'On Time'
}
{
year: '2020',
month: 'Feb',
date: '3',
inTime: '10:15',
outTime: '18:15',
status: 'Late'
}
{
year: '2020',
month: 'Feb',
date: '4',
inTime: '10:20',
outTime: '18:20',
status: 'Late'
}
]
]
empwhile in theforEachloop?