Append a subobject to an object using the spread operator

Let's assume that you have the following object:

javascript
let erik = {
    age: 30,
    location: {
        city: 'Barcelona',
        country: 'Spain'
    }
}

Now let's suppose that you want to copy the previous element and append an object to the location subproperty. For example, let's assume that you wish to append your ZIP Code (08038):

javascript
// Let's get a copy of the location object and append the ZIP Code
let _location = { ...erik.location, zip: '08038' }

// Now let's make a copy of the original object and replace the location subobject
let _erik = {...erik, location: _location }

You can do it in one line of code as well:

javascript
let _erik = {...erik, location: {...erik.location, zip: '08038' } }

And here is the result:

javascript
console.log(_erik)
/*
{
    age: 30
    location:{
        city: "Barcelona"
        country: "Spain"
        zip: "08038"
    }
}
*/

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.