简体   繁体   English

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

[英]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 .在第一行中,您已经将Address out 解构为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 .此外,由于您实际上并没有在任何地方使用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);

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

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

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