Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining on an Array.find() in JavaScript

I am getting into the habit of, depending on the context, converting some of my for loops to use array.find(). In so doing, I'm wondering if there's a way I can chain another operator on after the .find() in order to limit how much I grab from the object.

For instance, see the following:

currentStage = customerDoc.history.find(h => h.completed === false);
currentStageName = currentStage.name;

Since all I really want from here is the value for "currentStage.name", is there a way I can get this by chaining on after my find(), to specify I just want this property? If not, is there another way to do this in one line?

like image 283
Muirik Avatar asked Mar 20 '26 14:03

Muirik


1 Answers

Yes you can like this, notice the use of || {} to avoid exception in case the find returns undefined

currentStage = (customerDoc.history.find(h => h.completed === false) || {}).name

But IMO you should keep it like you have right now, it's readable and easy to maintain

currentStage = customerDoc.history.find(h => h.completed === false);
currentStageName = currentStage && currentStage.name;
like image 165
Code Maniac Avatar answered Mar 22 '26 02:03

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!