简体   繁体   中英

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}`;
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.

const episodeParser = (
    query: string, codeType ?: string, productId?: number, newProductId?: number
  ) => {
    let queryParams = { 
      query, 
      codeType, 
      processId : AppConfig.PROCESS_ID,
      ...(productId && {productId}),
      ...(newProductId && {newProductId})
    };
    return queryParams;
  }

Here, productId and newProductId both are optional, whatever the value of id will be there, these key will be getting in queryParams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM