ES6:用于解构的简短版本

时间:2018-08-28 16:45:01

标签: javascript ecmascript-6 destructuring

有没有办法将下面的代码写得短一些?

const { user } = JWT.verify(req.params.token, keys.secretOrKey);
const { email } = user;

我只需要JWT的email属性。

JWT.verify()返回的数据是一个对象:

user: {
    name: 'the name',
    email: 'email@address.com',
    ...
}

3 个答案:

答案 0 :(得分:4)

是的,您可以只写

const {user:{email}} = JWT.verify(req.params.token, keys.secretOrKey);

let test = { user: {
    name: 'the name',
    email: 'email@address.com'
    }}

const {user:{email}} = test;

console.log("user",typeof user);
console.log("email",email)

如您所见,仅设置了email,未定义user

不过请注意,只有在定义user的情况下,此方法才起作用,否则将引发错误。

您还可以为user对象设置默认值,如下所示:

let test = {/** user: {
    name: 'the name',
    email: 'email@address.com'
    }**/}

const {user:{email}={}} = test;

console.log("user",typeof user);
console.log("email",email)

如果未定义user,则不会引发错误

答案 1 :(得分:3)

如评论中所述:

const myFunction = {
  user: {
    name: 'the name',
    email: 'email@address.com'
  }
}

const {
  email
} = myFunction.user

console.log(email)

答案 2 :(得分:1)

解构任务非常强大:

-loss

请注意,此处未声明// shim for example const JWT = { verify: () => ({ user: { email: 'me@me.me', name: 'snek', }, }) }; /////////////////// const { user: { email } } = JWT.verify(); console.log(email);

在此处查看更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment