Object.assign—override nested property
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
}
}
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.
const target = {
a: { x: 0 },
b: { y: { m: 0, n: 1 } },
c: { z: { i: 0, j: 1 } },
d: null
}
const source1 = {
a: {},
b: { y: { n: 0 } },
e: null
}
const source2 = {
c: { z: { k: 2 } },
d: {}
}
function Object_assign (target, ...sources) {
sources.forEach(source => {
Object.keys(source).forEach(key => {
const s_val = source[key]
const t_val = target[key]
target[key] = t_val && s_val && typeof t_val === 'object' && typeof s_val === 'object'
? Object_assign(t_val, s_val)
: s_val
})
})
return target
}
console.log(Object_assign(Object.create(target), source1, source2))
You asked specifically for an ES6 way with Object.assign, but maybe someone else will prefer my more 'general' answer - you can do it easily with lodash, and personally I think that this solution is more readable.
import * as _ from 'lodash';
_.set(a, 'user.groups', newGroupsValue);
It mutates object.
You can change it this way,
const b = Object.assign({}, a, {
user: Object.assign({}, a.user, {
groups: {}
})
});
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
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()
The Object.create() method creates a new object with the specified prototype object and properties.
const b = Object.create(a)
b.user.groups = {}
// if you don't want the prototype link add this
// b.prototype = Object.prototype
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