skip to Main Content

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


  1. Chosen as BEST ANSWER

    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


  2. The way you are attempting to access the weekdays array inside the openingHours object is the problem. Mon is a property of openingHours, therefore using openingHours.mon works.

    However, weekdays is an array you’ve defined separately outside of openingHours and is not a property of openingHours.

    Instead of openingHours.weekdays[0] try openingHours[weekdays[0]]

    const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    
    const openingHours = {
      'Monday': {
        open: "9:00 AM",
        close: "6:00 PM"
      },
      'Tuesday': {
        open: "9:00 AM",
        close: "6:00 PM"
      },
      'Wednesday': {
        open: "9:00 AM",
        close: "6:00 PM"
      },
      'Thursday': {
        open: "9:00 AM",
        close: "6:00 PM"
      },
      'Friday': {
        open: "9:00 AM",
        close: "9:00 PM"
      },
      'Saturday': {
        open: "10:00 AM",
        close: "5:00 PM"
      },
      'Sunday': {
        open: "Closed",
        close: "Closed"
      }
    };
    
    console.log(openingHours[weekdays[0]]);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search