如果我有下面的对象,
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
。如果你把它想成一个函数会更容易——当你解构时
out 属性,原始对象不会保存在任何地方,也无法再访问。此处相同 - user
不再可访问。
如果你想访问它,你可以做的是从 user
中提取 type
,然后提取 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);
关于javascript - ES6 中的多级对象解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56841282/