I am exporting a variable which is an array from file1.js:
// file1.js
const myArray = [
{
"name": "Judah Hendricks",
"email": "diam@lobortis.net",
"hobbies": [
{
"sports": "tennis",
"recent": true
},
{
"sports": "football",
"recent": false
},
{
"sports": "volleyball",
"recent": false
}
]
},
{
"name": "Jakeem Olsen",
"email": "at@tellus.org",
"hobbies": [
{
"sports": "swimming",
"recent": false
},
{
"sports": "running",
"recent": true
}
]
}
];
module.exports = { myArray };
and I am using it inside a route:
//main.js
const { myArray } = require('./file1.js');
router.get('/getData', (req, res) => {
dataBase.users.findOne({ email: req.user.email }, function(error, data){
if (data){
const myDataClone = [...myArray];
let newData = [];
newData = myDataClone.map( dt => {
dt.oldHobbies = []
for (let i = 0; i < dt.hobbies.length; i++) { // Cannot read property 'length' of undefined
if (dt.hobbies[i].recent) {
dt.recentHobby = dt.hobbies[i];
} else {
dt.oldHobbies.push(dt.hobbies[i]);
}
}
delete dt.hobbies;
return dt;
})
return res.status(200).json({userInfo: newData})
} else {
// do another
}
});
}
when I hit this route for the first time, it returns the expected data. my problem is when I revisit this route for the second time, I get Cannot read property 'length' of undefined for the dt.hobbies
.
Could somebody help me understand what is wrong here and how to fix it?