I am mapping fetched data like this in React. I am printing name, column and row to the paragraph so whenever it is null, it prints just null null null, but if warehouse_name is null I need to transfer all values to some String like "Undefined" instead of these tree null.
There can be maybe better solution with using some string method for paragraph instead of this?
const transformedData = data.order_items.map((invoiceData) => {
return {
alternative_warehouse_position: invoiceData.alternative_warehouse_position,
warehouse_column: invoiceData.warehouse_column,
warehouse_name: invoiceData.warehouse_name,
warehouse_row: invoiceData.warehouse_row,
};
You could use the nullish coalescing operator ??.
const FALLBACK_STRING = "(not set)";
return {
alternative_warehouse_position: invoiceData.alternative_warehouse_position ?? FALLBACK_STRING,
warehouse_column: invoiceData.warehouse_column ?? FALLBACK_STRING,
warehouse_name: invoiceData.warehouse_name ?? FALLBACK_STRING,
warehouse_row: invoiceData.warehouse_row ?? FALLBACK_STRING,
};
3 ways to do it:
Using the "?" to check if its null. Example: ${Condition} ? ${is true} : ${is false}.
Using the new null-checking syntax. Example: ${Value} ?? ${the replacement if its null}
Using the OR operator, which enhances backwards capabilities. Example: ${first condition} || ${Second to replace if the first is false}
Note: Null counts as false
If I understand you correctly, you want to replace all three values with one string if invoiceData.warehouse_name is null. You can use the ternary operator (?:) for that.
const transformedData = data.order_items.map(
invoiceData => !!invoiceData.warehouse_name ?
{
alternative_warehouse_position: invoiceData.alternative_warehouse_position,
warehouse_column: invoiceData.warehouse_column,
warehouse_name: invoiceData.warehouse_name,
warehouse_row: invoiceData.warehouse_row
} :
"No data"
);