danday74 danday74 -4 years ago 37
Javascript Question

Destructuring nested objects as function parameters

In ES6 we can do:

let myFunc = ({name}) => {
console.log(name)
}

myFunc({name:'fred'}) // => logs 'fred'


But how do I do it for nested properties like this:

myFunc({event:{target:{name:'fred'}}}) // => I want it to log 'fred'


What should myFunc look like so that it logs 'fred'?

I cannot change the object passed in. I wish to use destructuring to achieve this or some other suitable ES6 approach.

Answer Source

You can simply do like this:

let myFunc = ({event: {target: {name}}}) => {
  console.log(name)
}

myFunc({event: {target: {name: 'fred'}}})
.as-console-wrapper { max-height: 100% !important; top: 0; }

Here is an other implementation, with both in parameters, but the second is entirely optionnal:

let myFunc = (
      {name: name},
      {event: {target: {name: eventTargetName = ''} = ''} = ''} = ''
    ) => {
      console.log(name, eventTargetName)
    }

myFunc({name:'fred'})
myFunc({name:'papi'}, {event: {target: {name: 'fredo'}}})
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download