Reputation: 447
I am working with an api that might or might not return any object properties. Therefore, I only want to get the value of the key if it exists.
As I need to get hundreds of values from the API I would love to find a way of handling undefined values globally (each value assignment is only executed if the key which it is looking for is found) instead of creating an if statement for each value I'm retrieving.
result.forEach((item, i) => {
let selectedLegend = Object.values(result[i]['legends']['selected'])[0];
if(selectedLegend['kills']){
datosTotales.kills += selectedLegend['kills'];
}
if(selectedLegend['wins_season_3']){
datosTotales.wins += selectedLegend['wins_season_3'];
}
if(selectedLegend['top_3']){
datosTotales.top3 += selectedLegend['top_3'];
}
// ...
// ...
});
Upvotes: 1
Views: 51
Reputation: 371019
One option is to destructure and have the properties default to 0 if they don't exist, then just add them up:
result.forEach((item, i) => {
const selectedLegend = result[i].legends.selected;
const { kills = 0, wins_season_3 = 0, top_3 = 0 } = Object.values(selectedLegend)[0];
datosTotales.top3 += kills + wins_season_3 + top_3;
});
If even that's too repetitive for you, then iterate over an array of property names:
result.forEach((item, i) => {
const selectedLegend = result[i].legends.selected;
const obj = Object.values(selectedLegend)[0];
for (const prop of ['kills', 'wins_season_3', 'top_3']) {
datosTotales.top3 += obj[prop] || 0;
}
});
Upvotes: 1