简体   繁体   中英

Object destructuring with Short-Circuit Evaluation

Is it possible to do achieve something like this?

const obj1 = { name: 'tom' }
const obj2 = { age: 20 }

let { name, age } = obj1 || obj2

Getting as a result -> name = 'tom' and age=20

The code above doesn't work, as it evaluates the condition one time and not on each variable assignment, which of course makes sense. It evaluates to name='tom', age=undefined

Is there any way to make that logic work?

Thanks!

You can merge the objects and then try to destructure like:

 const obj1 = { name: 'tom' } const obj2 = { age: 20 } let { name, age } = {...obj1, ...obj2}; console.log( name, age )

You can do this by

  let { name, age } = Object.assign({}, obj1, obj2)

This first create an object that has all the attributes of obj1 and the attributes of obj2.

Note this does not deeply copy attributes.

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