Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6/JS assign default value if array.find returns undefined

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;
like image 722
Dally Avatar asked Mar 26 '19 19:03

Dally


People also ask

Why is array find returning undefined?

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.

What does find() return in JavaScript?

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.

How do you assign default values to variables?

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.


2 Answers

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));
like image 171
Nina Scholz Avatar answered Oct 27 '22 07:10

Nina Scholz


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.

like image 34
noahtkeller Avatar answered Oct 27 '22 06:10

noahtkeller