I’m making a weather app and I need to insert weather icons for 4 different points of the forecast. The code for each icon is pretty much the same except I call pickIcon method on each of them. This method just returns the relative path of an svg icon based on the weather status passed to the method.
Is there a way to make this code less repetitive? Or am I overthinking this? I’m not sure if this kind of thing is considered good practice since I’m fairly new to programming. Thanks!
const icons = document.querySelector('.today-icons');
const icon600 = document.createElement('object'),
icon1200 = document.createElement('object'),
icon1800 = document.createElement('object'),
icon2200 = document.createElement('object');
icon600.className = 'weather-icon col col-3';
icon1200.className = 'weather-icon col col-3';
icon1800.className = 'weather-icon col col-3';
icon2200.className = 'weather-icon col col-3';
icon600.type = 'image/svg+xml';
icon1200.type = 'image/svg+xml';
icon1800.type = 'image/svg+xml';
icon2200.type = 'image/svg+xml';
icon600.data = `${this.pickIcon(weatherStatus600)}`;
icon1200.data = `${this.pickIcon(weatherStatus1200)}`;
icon1800.data = `${this.pickIcon(weatherStatus1800)}`;
icon2200.data = `${this.pickIcon(weatherStatus2200)}`;
icons.appendChild(icon600);
icons.appendChild(icon1200);
icons.appendChild(icon1800);
icons.appendChild(icon2200);
>Solution :
let data = [weatherStatus600, weatherStatus1200, weatherStatus1800, weatherStatus2200];
const icons = document.querySelector('.today-icons');
for(const d of data) {
const icon = document.createElement('object');
icon.className = 'weather-icon col col-3';
icon.type = 'image/svg+xml';
icon.data = `${this.pickIcon(d)}`;
icons.appendChild(icon);
}
This should work!