2

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!

Franco Muñiz
  • 811
  • 1
  • 10
  • 21
  • 1
    Object destructuring works against a single object only (with that syntax). You must merge the two objects first. – briosheje Mar 19 '20 at 16:20

2 Answers2

2

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 )
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • Makes complete sense, don't know why I didn't think about this before haha. Thanks! Will accept the answer as soon as the site allows me to – Franco Muñiz Mar 19 '20 at 16:20
  • 1
    This is my preferred method. Works quite well. You can also have duplicate keys and the objects listed later can override the earlier ones. You can have an object with all the defaults as the first object, then have one or more with the non-default values. – samanime Mar 19 '20 at 16:29
1

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.

cementblocks
  • 4,326
  • 18
  • 24