12

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.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
danday74
  • 52,471
  • 49
  • 232
  • 283
  • Do you know the structure of `name`? Or are you wanting to log all values? – Adam Paxton Jun 12 '17 at 15:39
  • the object structure is show ... event.target.name ... i just want to log the value of event.target.name using ES6 destructuring if possible – danday74 Jun 12 '17 at 15:40

3 Answers3

15

You can simply do like this:

const 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:

const 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; }
john
  • 296
  • 1
  • 9
2

Try this:

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

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

See also examples on MDN.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
1

You can do:

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

myFunc({ event: { target: { name: 'fred' } } });

Or:

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

myFunc({ event: { target: { name: 'fred' } } });
Adam Paxton
  • 1,422
  • 1
  • 12
  • 11