1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

let {Address:myAddress, {city: myCity, country: myCountry}}=personObj this way inlien to assign to is it possible
Once you destructure an object, Address ( in this case ), you won't have a reference of it anymore. So if you want to have an handle of both myAddress, then you will have to pick them again. let { Address : myAddress, Address: { city: myCity, country: myCountry } } = personObj
1

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

1 Comment

That last one is the one I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.