[英]Destructuring nested objects as function parameters
In ES6 we can do: 在ES6中我们可以做到:
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'? myFunc应该是什么样的,以便记录'fred'?
I cannot change the object passed in. I wish to use destructuring to achieve this or some other suitable ES6 approach. 我不能改变传入的对象。我希望使用解构来实现这个或其他一些合适的ES6方法。
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: 这是另一个实现,两个参数都有,但第二个完全是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; }
Try this: 试试这个:
let myFunc = ({ event: { target: { name } } }) => { console.log(name); }; myFunc({ event: { target: { name:'fred' } } }); // => logs 'fred'
See also examples on MDN . 另请参阅MDN上的示例 。
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' } } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.