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
?
Here's a small function called
Object_assign
(just replace the.
with a_
if you need nested assigning)The function sets all target values by either pasting the source value in there directly, or by recursively calling
Object_assign
again when both the target value and source value are non-null
objects.assign method will make a new object by copying from the source object, the issue if you change any method later on in the source object it will not be reflected to the new object.
Use create()
This way you have b linked to a via the prototype and if you make any changes in a it will be reflected in b, and any changes in b will not affect a
More general solution below. It makes recursively assigning only if there are conflicts (same key names). It resolves issues assigning complex objects, which has many reference points. For example,
nested-object-assign
, an existing package for nested object assign in npm, stuck with complex objects assign because it recursively goes through all keys.You can change it this way,
or just do,
Small fine tune of phillips first answer.
when having nested object i prefer using this little hack .