简体   繁体   中英

How to conditionally set an object property when the asignee is undefined

I am trying to conditionally set an object property in JS, but am getting the following error.

TypeError: Cannot read property 'address' of undefined

This is being thrown by secondary.address .

let address = {
  prop: primary.address || secondary.address || null
};

Is there a clean way to set address.prop in a cascading fashion by casting secondary.address to null instead of throwing an error?

You can use shorCircuiting &&

let address = {
  prop: primary && primary.address || secondary && secondary.address || null
};

Or you can use Optional Chaining this is stage 2 proposal, if your project already using babel you can use babel-plugin-proposal-optional-chaining

let address = {
  prop: primary?.address || secondary?.address || null
};

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