skip to Main Content

I have an array of objects

const workSchedule = [
    {
        name: 'a',
        age: 21,
        workDays: {
            monday: {isavailable:true}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:true}, Friday:{isavailable:false}
        }
    },
    {
        name: 'b',
        age: 22,
        workDays: {
            monday: {isavailable:false}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:false}, Friday:{isavailable:false}
        }
    }
]

and I have a string variable which have a selected Day

 const day='Monday'

Now I want to check if the person A or B is available on monday or not?

2

Answers


  1. You can achieve this simply with filter method.

            const day = 'monday';
            const workSchedule = [
            {
                name: 'a',
                age: 21,
                workDays: {
                    monday: {isavailable:true}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:true}, Friday:{isavailable:false}
                }
            },
            {
                name: 'b',
                age: 22,
                workDays: {
                    monday: {isavailable:false}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:false}, Friday:{isavailable:false}
                }
            }
        ];
    
        
    const available = workSchedule.filter(sch=> sch.workDays[day.toLowerCase()].isavailable === true);
    
    
    console.log(available[0]);
    console.log(available[0].name);
    Login or Signup to reply.
  2. Try like this,

      const workSchedule = [
        {
          name: "a",
          age: 21,
          workDays: {
            monday: { isavailable: true },
            tuesday: { isavailable: false },
            wednesday: { isavailable: true },
            thursday: { isavailable: true },
            friday: { isavailable: false },
          },
        },
        {
          name: "b",
          age: 22,
          workDays: {
            monday: { isavailable: false },
            tuesday: { isavailable: false },
            wednesday: { isavailable: true },
            thursday: { isavailable: false },
            friday: { isavailable: false },
          },
        },
      ];
    
      const day = "Monday";
    
      workSchedule.forEach((e) => {
        if (e.workDays[day.toLocaleLowerCase()]["isavailable"]) {
          console.log(e.name + " is available");
        } else {
          console.log(e.name + " is not available");
        }
      });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search