I'm trying to get a JSON array of objects with a for loop but for some reason it only works if I pass the index explicitly as a number (e.g. parseJSON.sites[0]). If I use a variable, which I would prefer in this example because of the loop, the shown example doesn't work.
let openJSON = fs.readFileSync('./pages/jsons/main.json', 'utf-8');
let parseJSON = JSON.parse(openJSON);
for (let i = 0; i <= 4; i++) {
//this code doens't work and return: Cannot read property 'name' of undefined
main.push(parseJSON.sites[i]["name"]);
//this code works, and returns what i expected
main.push(parseJSON.sites[0]["name"]);
}
//main.json
{
"sites": [
{ "name": "stackoverflow", "url": "stackoverflow.com" },
{ "name": "Youtube", "url": "www.youtube.com" },
]
}
I have no idea why this code doesn't work. I already tried to change the name of the variable i, in case of any conflict but it still returns the same error. I also tried to execute the code snippet without the .push() method.
parseJSONvariable.