How can I rewrite this code to foreach?

  • 0
    const seasons = {
      SUMMER: {
        BEGINNING: "summer.beginning",
        ENDING: "summer.ending"
      },
      WINTER: "winter",
      SPRING: "spring",
      AUTUMN: "autumn"
    };
    
    let season = seasons.SUMMER.BEGINNING;
    
    if (!season) {
      throw new Error("Season is not defined");
    }
    
    switch (season) {
      case seasons.SUMMER.BEGINNING:
      // Do something for summer beginning
      case seasons.SUMMER.ENDING:
      // Do something for summer ending
      case seasons.SUMMER:
      // This will work if season = seasons.SUMMER
      // Do something for summer (generic)
      case seasons.WINTER:
      //Do something for winter
      case seasons.SPRING:
      //Do something for spring
      case seasons.AUTUMN:
      //Do something for autumn
    }
    JavaScript Anonymous, Jan 29, 2020

  • 3 Answers
  • 0
    forEach is an array method, where are the arrays?
    Layla Wilcox

  • 0
    Cast an object to an array. Object.keys, Object.values ​​and Object.entries to help
    Anonymous

  • 0
    Not how. forEach processes the array and performs some function for each value. In your case, it is not required to process all keys, but only one
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!