13

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.

2
  • Do you know the structure of name? Or are you wanting to log all values? Commented Jun 12, 2017 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 Commented Jun 12, 2017 at 15:40

3 Answers 3

16

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; }

Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

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

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

See also examples on MDN.

Comments

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' } } });

1 Comment

OP asked for solution with destructuring or some other ES 6 approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.