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?
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;