ES6中的多级对象分解

阿卡什

如果我有以下对象,

const obj = {
   user:
   {
    type:{
      type1:"developer",
      type2:"architect"
    },
    role:"admin"
   },
   salary:50000
}

const {user: {type}} = obj;
console.log(`type:  ${type}`);
console.log(user);

如果我写下面这样的话

const {user: {type}} = obj;
console.log(type);  //prints [object Object] which is right

但是如果我尝试打印

console.log(user); // ReferenceError: user is not defined 

有人可以向我解释一下ES6解构的以下内容吗?

const {user: {type}} = obj;
杰克·巴什福德

当前,您正在做的是获取user子对象,并type从中提取子对象如果您将其像函数那样考虑,则会更容易-分解属性时,原始对象不会保存在任何地方,并且不再可以访问。此处相同-user无法访问。

如果你想访问它会提取你可以做什么typeuser,还提取user,并保持它。

const obj = {
  user: {
    type: {
      type1: "developer",
      type2: "architect"
    },
    role: "admin"
  },
  salary: 50000
}

const { user: { type }, user } = obj;
console.log(`type:  ${type}`);
console.log(user);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章