Sorry for this, maybe is an easy and basic question
I'm getting results from an endpoint but some of these values could be empty, then on my screen shows "undefined"
How can I check in a clean code if some of the value is undefined then show nothing?
myvalues() {
if (!this.myendpointdata) {
return '';
}
const { value1, value2, value3, value4 } =
this.myendpoindata.master.values;
return `${value1} ${value2} ${value3} ${value4}`;
}
This is my code. And, for example, value2 shows undefined
You can set empty strings if your values are undefined
myvalues() {
if (!this.myendpointdata) {
return '';
}
const { value1, value2, value3, value4 } =
this.myendpoindata.master.values;
return `${value1 || ""} ${value2 || ""} ${value2 || ""} ${value4 || ""}`;
}
You also can loop through values and filter not undefined values out for display
myvalues() {
if (!this.myendpointdata) {
return '';
}
const { value1, value2, value3, value4 } = this.myendpoindata.master.values;
const values = Object.values({ value1, value2, value3, value4 });
return values.filter(value => !value).join(" ");
}
You can use ternary operations:
return `${value1 ? value1 : ''} ${value2 ? value2 : ''} ${value3 ? value3 : ''} ${value4 ? value4 : ''}`;