skip to Main Content

I would like to avoid redundant if, for this I wanted to set up a switch/case. My goal is to look in my JSON object if for a day associated boolean is true or false. In the case or if it is true I add the number of the day in a table.

My object:

let days = [

{
  "monday": true,
  "tuesday": true,
  "wednesday": true,
  "thursday": true,
  "friday": true,
  "saturday": true,
  "sunday": true
}
]

What I tried but it’s not working:

  let nbrsDay = []
    Object.getOwnPropertyNames(days).forEach(function (key) {
        switch (key) {
            case "monday" === true:
                nbrsDay .push(2);
                break;
            case "tuesday" === true:
                nbrsDay .push(3);
                break;
            case "wednesday" === true:
                nbrsDay .push(4);
                break;
            case "thursday" === true:
                nbrsDay .push(5);
                break;
            case "friday" === true:
                nbrsDay .push(6);
                break;
            case "saturday" === true :
                nbrsDay .push(7);
                break;
            case "sunday"  === true:
                nbrsDay .push(1);
                break;
        }
    });
    return nbrsDay 

Someone have a method to do this?

2

Answers


  1. let daysArray = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]
    
    let nbrOfDay = []
    
    let daysObject= {
      "monday": true,
      "tuesday": true,
      "wednesday": true,
      "thursday": true,
      "friday": true,
      "saturday": true,
      "sunday": true
    }
    
    Object.keys(daysObject).forEach(function (key) {
        if(daysObject[key]){
            let keyIndex = daysArray.indexOf(key)+1
            nbrOfDay.push(keyIndex)
        }
    })
    
    console.log(nbrOfDay)
    Login or Signup to reply.
  2. simply:

    const 
      days = [{ monday: true, tuesday: true, wednesday: true, thursday: true, friday: true, saturday: true, sunday: true }] 
    , daysCount = { monday: 2, tuesday: 3, wednesday: 4, thursday: 5, friday: 6, saturday: 7, sunday: 1} 
      ;   
    
    let nbrsDay = Object.keys(days[0]).reduce( (nbrs,dayName) => 
      {
      if (days[0][dayName])
        nbrs.push(daysCount[dayName]);
      return nbrs
      }, []);
     
    console.log('nbrsDay =', JSON.stringify(nbrsDay) );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search