Search code examples
javascriptobjectdestructuringobject-destructuringshort-circuit-evaluation

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!


Solution

  • 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 )