in javascript:
const weekdays = [‘mon’, ‘tue’,…
console.log(openingHours.mon); // works
console.log(weekdays[0]); // works, returns mon
console.log(openingHours.weekdays[0]); // fails with Uncaught TypeError: Cannot read properties of undefined (reading ‘0’)
why
tried console.log(openingHours.weekdays[0].toString());
failed also
2
Answers
weekdays[0] is not a property of openingHours so brackets must be used:
console.log('fixed', openingHours[weekdays[0]]);
rooky mistake, sorry if I wasted your time
The way you are attempting to access the
weekdays
array inside theopeningHours
object is the problem. Mon is a property ofopeningHours
, therefore usingopeningHours.mon
works.However,
weekdays
is an array you’ve defined separately outside ofopeningHours
and is not a property ofopeningHours
.Instead of
openingHours.weekdays[0]
tryopeningHours[weekdays[0]]