-1

I have a variable and I want to destructure it

const myFunc = ({name}) => {
  console.log(name)
}
myFunc({name: 'hey'})

But what if the variable is not there?

const myFunc = ({name}) => {
  console.log(name)
}
myFunc({name2: 'hey'})

It just says undefined, which is fine

But what if I am destructuring more?

const myFunc = ({name, structure: {type}}) => {
  console.log(name)
  console.log(type)
}
myFunc({name: 'hey', structure : {type: 'hay'}})

Ok, but what if the parameter is not there?

const myFunc = ({name, structure: {type}}) => {
  console.log(name)
  console.log(type)
}
myFunc({name2: 'hey', structure2 : {type: 'hay'}})

Then it gives an (expected) error

The question is, how can I cope with these situations while destructuring in the same sentence? Or am I forced to destructure in 2 steps?

georg
  • 211,518
  • 52
  • 313
  • 390
GWorking
  • 4,011
  • 10
  • 49
  • 90

1 Answers1

0

SOLVED:

The question is duplicated from JS/ES6: Destructuring of undefined

But still, this one may be of use if only looking at this particular problem

const myFunc = ({name, structure: {type} = {}}) => {
  console.log(name)
  console.log(type)
}
myFunc({name2: 'hey', structure2 : {type: 'hay'}})
GWorking
  • 4,011
  • 10
  • 49
  • 90