P. Fernandez P. Fernandez - 5 months ago 16
JSON Question

Several Keys with Same Value in JavaScript Object

I am building a weather app for my website using JavaScript, jQuery, html and css. I am getting my weather data from an api. The api has several different possibilities for current condition, such as Rain, Snow, etc. I am using an open source weather icon pack that I found online. My intention is to associate an appropriate icon with each possible condition that could be fed back to my app from the api. The approach that I decided on, and mind you that I am totally brand new at web and JavaScript development so this may not even be a good idea, but I decided to create an object with key value pairs. The keys would be comprised of all of the potential conditions, while the value would be the class name of the appropriate html icon for that condition. Here is a snippet of what I am talking about.

var condition = data.current.weather; //value coming from API

var allConditions = {
Light Drizzle: 'wi wi-showers',
Heavy Drizzle: 'wi wi-showers',
Drizzle: 'wi wi-showers',
Light Rain: 'wi wi-rain',
Heavy Rain: 'wi wi-rain',
Rain: 'wi wi-rain',
Light Snow: 'wi wi-snow',
Heavy Snow: 'wi wi-snow',
Snow: 'wi wi-snow',
Light Snow Grains: 'wi wi-snow'
}

$('#icon').addClass(allConditions[currentCondition]);


As you can see, there are several conditions for which I will be utilizing the same icon, so in other words, there are several keys in the object with the same value. Is there some way that I can assign the same value to several keys? For example something like...

var allConditions = {
'Light Drizzle, Heavy Drizzle,
Light Rain , Heavy Rain' : 'wi wi-showers',
'Light Snow, Heavy Snow' : 'wi wi-snow'
}


I know that this example won't work, but I use it here just to visulize what I am trying to accomplish. For now I will just give each and every key its own value, even if that value is the same for several other key, but if there is a way to optimize this I would love to know about it!

Answer

Instead of storing this data in an object literal, you may want to write a function that accepts the weather condition as an argument and returns the proper class. It may even be a good use case for a switch statement.

function conditionToClass(condition) {
  var className = 'wi wi-';

  switch (condition) {
    case 'Drizzle':
    case 'Light Drizzle':
    case 'Heavy Drizzle':
      return className + 'showers';
    case 'Rain':
    case 'Light Rain':
    case 'Heavy Rain':
      return className + 'rain';
    case 'Snow':
    case 'Light Snow':
    case 'Heavy Snow':
    case 'Light Snow Grains':
      return className + 'snow';
    default:
      return 'some-default-class';
  }
}

var weatherClass = conditionToClass(data.current.weather);

$('#icon').addClass(weatherClass);