简体   繁体   中英

Javascript ES6 Destructuring Nested Object Parent and Child Assign variable

I Destructuring first variable nested objects within parent then I declare another variable to set a child value but there some error I don't know which sufficient way to solve this and readable

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

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

In the first line, you have already destructured, Address out into myAddress . So you would not require one more layer of nesting when de structuring it.

 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);

Also since you are not really using myAddress anywhere, you can just destructure this out from 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);

I think you're looking for

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

or

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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