Reputation: 6289
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?
Upvotes: 2
Views: 4014
Reputation: 51
You could use optional chaining (which was introduced with ECMAScript 2020):
const currentStageName = customerDoc.history.find(h => !h.completed)?.name;
Upvotes: 5
Reputation: 11
you could also chain a .map onto the find results in order to limit and/or reshape what gets returned by wrapping it in an array (and using filter if no results are found), e.g.
currentStage = [customerDoc.history.find(h => h.completed === false)].filter(h => h != undefined).map(h => ({'name':h.name}))[0]
Upvotes: 1
Reputation: 37755
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;
Upvotes: 5
Reputation: 191986
Use short-circuit evaluation to have a default object in case nothing if found, and destructuring to get the property you want. If nothing is found, the result would be undefined
:
const { name: currentStageName } = customerDoc.history.find(h => h.completed === false) || {};
Upvotes: 3