I have an object with arrays (the numbers are codes I get from API):
const weatherConditions = {
rainy: [365, 362, 359, 356, 353, 320, 317, 314, 311, 308, 305, 302, 299, 296, 293, 284, 281, 266, 263, 185, 182, 176, 143],
snowy: [371, 368, 338, 335, 332, 329, 326, 323, 230, 227, 179],
sunny: [113],
partlyCloudy: [116],
cloudy: [122, 119],
foggy: [260, 248],
storm: [395, 392, 389, 386],
thunder: [200],
hailing: [377, 374, 350],
};
A function that runs through the object keys and finds the number the API sent. It returns a string value of the object key (sunny, cloudy etc.):
const findByCode = (code) => {
console.log(
Object.keys(weatherConditions).find((key) => {
return weatherConditions[key].includes(code);
}),
);
};
A switch case, that chooses a picture respectively the function return value. But it always runs to default straight away. I don't see the issue. (weatherCode is an API value, 100% correct);
switch (findByCode(weatherCode)) {
case 'rainy':
img.src = './img/rain.png';
break;
case 'snowy':
img.src = './img/snow.png';
break;
case 'sunny':
img.src = './img/sun.png';
break;
case 'partlyCloudy':
img.src = './img/partly-cloudy.png';
break;
case 'cloudy':
img.src = './img/clouds.png';
break;
case 'foggy':
img.src = './img/fog.png';
break;
case 'storm':
img.src = './img/storm.png';
break;
case 'thunder':
img.src = './img/thunder.png';
break;
case 'hailing':
img.src = './img/hail.png';
break;
default:
img.src = './img/weather-news.png'
break;
}
CodePudding user response:
I think the console.log()
is the problem in findByCode
replace it with a return
statement and it will work.