最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ecmascript 6 - JavaScript: destructuring with a conditional statement - Stack Overflow

programmeradmin1浏览0评论

I would like to get firstName and lastName properties from a whole user object. I need to use a conditional statement too. How to do something like that?

getUserById(id)and getUserByAddress(id) use the JavaScript find() method that returns an element or undefined.

let { firstName, lastName } = getUserById(id);
if ({ firstName, lastName } === undefined) {
  { firstName, lastName } = getUserByAddress(id);
}
return `${firstName} ${lastName}`;

I would like to get firstName and lastName properties from a whole user object. I need to use a conditional statement too. How to do something like that?

getUserById(id)and getUserByAddress(id) use the JavaScript find() method that returns an element or undefined.

let { firstName, lastName } = getUserById(id);
if ({ firstName, lastName } === undefined) {
  { firstName, lastName } = getUserByAddress(id);
}
return `${firstName} ${lastName}`;
Share Improve this question edited Oct 19, 2018 at 13:47 Flora asked Oct 19, 2018 at 13:23 FloraFlora 5631 gold badge9 silver badges19 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 22
const { firstName, lastName } = getUserById(id) || getUserByAddress(id) || {};
if (firstName && lastName) {
    return `${firstName} ${lastName}`;
}
return "Unknown user";

If getUserById(id) is falsy, getUserByAddress(id) will be executed. If this is falsy, too, {} will at least prevent throwing an error.

发布评论

评论列表(0)

  1. 暂无评论