我在父对象中解构了第一个变量嵌套对象,然后我声明了另一个变量来设置子值,但是有一些错误,我不知道有什么足够的方法可以解决这个问题并且可读
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);