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

Dal*_*lly 9 javascript ecmascript-6

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;
Run Code Online (Sandbox Code Playgroud)

noa*_*ler 8

我看到这已得到回答,但我认为这可能有所贡献

const { amount = 0 } = response.data.find(t => t.paymentType === 'RF' && t.status === 1) || {};
this.statistics.creditAmount = amount;
Run Code Online (Sandbox Code Playgroud)

或者你可以使用减速器:

  this.statistics.creditAmount = response.data.reduce((amt, t) => t.paymentType === 'RF' && t.status === 1 ? t.amount : amt, 0);
Run Code Online (Sandbox Code Playgroud)

减速器在遍历整个数组时会使用更多的时钟周期,而Array.prototype.find一旦到达第一个匹配项就会停止。这也可能导致结果发生变化,因为 reducer 的编写方式将从匹配的数组中获取最后一项。


Deh*_*hli 5

The problem with your code is that you're accessing .amount of undefined for cases where array.find returns undefined. You can solve it by adding a guard:

const credit = response.data.find(t => 
  t.paymentType == 'RF' && t.status == 1);

this.statistics.creditAmount = credit ? credit.amount : 0;

Run Code Online (Sandbox Code Playgroud)