Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.assign—override nested property

I have an Object a like that:

const a = {   user: {    …    groups: […]    …   } } 

whereby there are a lot more properties in a.user

And I would like to change only the a.user.groups value. If I do this:

const b = Object.assign({}, a, {   user: {     groups: {}   } }); 

b doesn't have any other Property except b.user.groups, all others are deleted. Is there any ES6 way to only change the nested property, without loosing all the other, with Object.assign?

like image 311
philipp Avatar asked Jan 11 '17 10:01

philipp


People also ask

Does object assign overwrite properties?

Description. Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object.

How do I change nested objects?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

Does object assign do a deep copy?

Object. assign does not copy prototype properties and methods. This method does not create a deep copy of Source Object, it makes a shallow copy of the data. For the properties containing reference or complex data, the reference is copied to the destination object, instead of creating a separate object.


1 Answers

After some trying I could find a solution that looks pretty nice like that:

const b = Object.assign({}, a, {   user: {     ...a.user,     groups: 'some changed value'   } }); 

To make that answer more complete here a tiny note:

const b = Object.assign({}, a) 

is essentially the same as:

const b = { ...a } 

since it just copies all the properties of a (...a) to a new Object. So the above can written as:

 const b = {    ...a,          //copy everything from a    user: {        //override the user property       ...a.user,  //same sane: copy the everything from a.user       groups: 'some changes value'  //override a.user.group    }  } 
like image 153
philipp Avatar answered Sep 20 '22 08:09

philipp