I have a method which returns a value from an element in the array. Not all the elements have the property I want to return. I would like to do this function with one line using the method find()
. I've tried this way to solve it:
getExecsFromTour(tourId){
return this.repInfo.find(el => el.id == tourId ).execs || [];
}
But the elements which don't contain the property execs
return an error of undefined
.
To solve it, I had to store the result in a local variable:
getExecsFromTour(tourId){
let items = this.repInfo.find(el => el.id == tourId);
return items != undefined ? items.execs : [];
}
But I would like to know if I am missing something and this function can be achieved with one sentence.
(this.repInfo.find(el => el.id == tourId) || {}).execs || [];
– Jimmiejimmy{}
statment >.<. @Jehiah You're right, but I was curious about how to solve this, because it might help me in the future! – Wiredraw