Sunday, May 19, 2024
44
rated 0 times [  48] [ 4]  / answers: 1 / hits: 80494  / 8 Years ago, wed, january 11, 2017, 12:00:00

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?


More From » ecmascript-6

 Answers
38

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
}
}

[#59393] Sunday, January 8, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braydon

Total Points: 0
Total Questions: 102
Total Answers: 111

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;