Destructuring nested objects as function parameters

爷,独闯天下 提交于 2020-07-29 06:32:56

问题


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.


回答1:


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



回答2:


Try this:

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

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

See also examples on MDN.




回答3:


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


来源:https://stackoverflow.com/questions/44503409/destructuring-nested-objects-as-function-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!