解构嵌套对象作为函数参数 [英] Destructuring nested objects as function parameters

查看:68
本文介绍了解构嵌套对象作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ES6中,我们可以这样做:

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'

myFunc应该是什么样,以便记录"fred"?

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

我无法更改传入的对象.我希望使用解构来实现此方法或其他一些合适的ES6方法.

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

推荐答案

您可以这样做:

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

这篇关于解构嵌套对象作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆