JS: Handle with find() property undefined

て烟熏妆下的殇ゞ 提交于 2019-12-12 17:14:31

问题


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.


回答1:


You seem to have the general idea, Array.prototype.find will search the array for the first element which, when used as an argument of the callback, will have the callback return a truthy value. If nothing is found, it returns undefined.

Your code should work, but yes, one way to do it in one line (if you want) is to use:

getExecsFromTour(tourId){
  return (this.repInfo.find(el => el.id == tourId) || {}).execs || [];
}

If Array.prototype.find returns undefined, the first inner parenthetical expression will be evaluated to empty object, which can attempt (and fail) to access the .execs key without a TypeError, which will also evaluate to undefined, in which case the function returns empty array, which is what your code above does.

EDIT: Someone commented this solution already, lol, but as the comments say, nothing wrong with keeping it multiline (more readable that way).




回答2:


what about

getExecsFromTour(tourId){
     return this.repInfo.find(el => 'execs' in el && el.id == tourId ).execs || [];
}

...

EDITED

var a = [{execs : 1, id:4}, {id:5}];
function getExecsFromTour(tourId, x){
    return (x = a.find(el => 'execs' in el && el.id == tourId )) ? x.execs : [];
}

this time at least I ran it couple of times



来源:https://stackoverflow.com/questions/52389757/js-handle-with-find-property-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!