Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: destructuring with a conditional statement

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}`;
like image 711
Flora Avatar asked Dec 01 '22 10:12

Flora


1 Answers

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.

like image 118
Matthi Avatar answered Dec 04 '22 01:12

Matthi