简体   繁体   中英

How to change nested object attribute using JavaScript spread operator?

I have a JavaScript object like below

const obj = {
    name: 'Jone',
    location: {
        presentAddress: {
            livingAddress: {
                City: {name: 'New York'},
                Country: {name: 'USA'},
            }
        }
    }

}

I'm trying to change city name New York to London

So, I have tried below code

console.log({
    ...obj,
    location:{
        ...obj.location,
        presentAddress:{
            ...obj.location.presentAddress,
            livingAddress: {
                ...obj.location.presentAddress.livingAddress,
                City:{
                    ...obj.location.presentAddress.livingAddress.City,
                    name: "London"
                }
            }
        }
    }
})

It's working fine, My question is has there any shorter way to do this change?

Try setting the nested property directly.

obj.location.presentAddress.livingAddress.City.name = "London"

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