我解构父级中的第一个变量嵌套对象,然后声明另一个变量来设置子值,但出现一些错误,我不知道哪种足够的方法可以解决这个问题并且可读
let personObj = {
Name: 'Robiul',
Age: 22,
Address: {
city: 'Dhaka',
country: 'Bangladesh'
}
}
let {Address: myAddress} = personObj
let {myAddress:{city: myCity, country: myCountry}}=myAddress
最佳答案
在第一行中,您已经将 Address
解构为 myAddress
。
因此,在解构它时,您不需要再嵌套一层。
let personObj = {
Name: 'Robiul',
Age: 22,
Address: {
city: 'Dhaka',
country: 'Bangladesh'
}
}
// destructure address and rename it to myAddress
let { Address: myAddress } = personObj;
// destructure myAdress and rename city and country
let { city: myCity, country: myCountry } = myAddress;
console.log('city', myCity, 'country', myCountry);
此外,由于您并未真正在任何地方使用 myAddress
,因此您可以从 personObj
中解构它。
let personObj = {
Name: 'Robiul',
Age: 22,
Address: {
city: 'Dhaka',
country: 'Bangladesh'
}
}
// destructure address and rename it to myAddress
let {
Address: {
city: myCity,
country: myCountry
}
} = personObj;
console.log('city', myCity, 'country', myCountry);
关于Javascript ES6 解构嵌套对象父级和子级分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61488160/