I tried looking at other questions but I can't find a proper solution. I'm retrieving a GET response and I'm storing it into a variable, then I'm parsin that array in order to find daily occurrences. The code works, but once it reaches the forEach it complains with:
Cannot read property 'forEach' of undefined
. Here's my code:
var myObj;
fetch('https://blashblashblash.com?param1')
.then(res=>res.json())
.then(data=>myObj= data)
.then(() => console.log(myObj));
var myRes = [];
myObj.forEach(function (elem) {
var date = elem.CreationDate.split(' ')[0];
if (myRes [date]) {
myRes [date] += 1;
} else {
myRes [date] = 1;
}
});
That's the content of myObj once it finished:
[{Id, Var1, Var2, CreationDate},
{1, 123, Var2, 2020-12-11},
{2, 1234, Var2, 2020-12-12},
{3, 12345, Var2, 2020-12-12},
{4, 1234, Var2, 2020-12-13},
{5, 321, Var2, 2020-12-15},
{6, 3214, Var2, 2020-12-15},
{7, 5432, Var2, 2020-12-16}]
where am I wrong? If I'm executing the code in different steps it works correctly.
EDIT: Here's my updated code:
var myObj;
var myRes= [];
fetch('https://blashblashblash.com?param1')
.then(res=>res.json())
.then(data=>myObj= data)
.then(() => {
myObj.forEach(function (elem) {
var date = elem.CreationDate.split(' ')[0];
if (myRes[date]) {
myRes[date] += 1;
} else {
myRes[date] = 1;
}
});
});
var finalResult= {};
dates.forEach(date => {
if(!myRes.hasOwnProperty(date)) {
finalResult[date] = 0;
} else {
finalResult[date] = myRes[date];
}
return finalResult;
});
If I'm executing the whole my finalResult is empty, while if I'm executing it in blocks it works. If I'm inserting the myRes =[] inside the last .then it complains it can't find it. Where am I wrong?