How do I set a default value to a variable if array.find returns 'undefined'.
Here's the line that's causing me issues. In some instances this variable will populate but in others, it won't and in that case, I want it to default to 0.
this.statistics.creditAmount = response.data.find(t => t.paymentType == 'RF' && t.status == 1).amount || 0;
The Array. find() method returns an undefined value if the condition implemented in the callback function is never satisfied or you haven't returned a value from the callback function. To solve this, use a type guard to check if find returned a value before accessing properties or methods.
JavaScript Array find() The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found.
The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.
Another approach is to use a closure and a destructuring with a default object/value.
const
getAmount = ({ amount = 0 } = {}) => amount,
credit = getAmount(response.data.find(t => t.paymentType == 'RF' && t.status == 1));
I see this has been answered but I thought this could contribute
const { amount = 0 } = response.data.find(t => t.paymentType === 'RF' && t.status === 1) || {};
this.statistics.creditAmount = amount;
Or you could use a reducer:
this.statistics.creditAmount = response.data.reduce((amt, t) => t.paymentType === 'RF' && t.status === 1 ? t.amount : amt, 0);
The reducer would use more clock cycles as it traverses the entire array, whereas Array.prototype.find
stops once it reaches the first match. This may cause the results to vary as well, since the way that reducer is written it will take the last item from the array that matches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With