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,
};
CodePudding user response:
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
CodePudding user response:
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,
};
CodePudding user response:
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"
);
CodePudding user response:
If what you want to do is to return the "Undefined" string instead of null, then you could try the following code instead:
const transformedData = data.order_items.map((invoiceData) => {
return {
alternative_warehouse_position: invoiceData.alternative_warehouse_position || "Undefined",
warehouse_column: invoiceData.warehouse_column || "Undefined",
warehouse_name: invoiceData.warehouse_name || "Undefined",
warehouse_row: invoiceData.warehouse_row || "Undefined",
}});
If this isn't what you mean, could you elaborate further, especially on the "...but if warehouse_name is null I need to transfer all values to some String like "Undefined" instead of these tree null." part of the problem statement?