繁体   English   中英

Javascript ES6 解构嵌套 Object 父子赋值变量

[英]Javascript ES6 Destructuring Nested Object Parent and Child Assign variable

我在父对象中解构第一个变量嵌套对象然后我声明另一个变量来设置子值但是有一些错误我不知道哪种方法可以解决这个问题并且可读

let personObj = {
        Name: 'Robiul',
        Age: 22,
        Address: {
            city: 'Dhaka',
            country: 'Bangladesh'
        }
    }

    let {Address: myAddress} = personObj
    let {myAddress:{city: myCity, country: myCountry}}=myAddress

在第一行中,您已经将Address out 解构为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);

我想你正在寻找

const {Address: myAddress} = personObj;
const {city: myCity, country: myCountry} = myAddress;
console.log(myAddress, myCity, myCountry);

或者

const {Address: {city: myCity, country: myCountry}} = personObj;
console.log(myCity, myCountry); // notice no myAddress variable

或者

const {Address: myAddress, Address:{city: myCity, country: myCountry}} = personObj;
console.log(myAddress, myCity, myCountry);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM