我有一个像这样的对象a:
const a = {
user: {
…
groups: […]
…
}
}在a.user中有更多的属性
我只想更改a.user.groups值。如果我这么做:
const b = Object.assign({}, a, {
user: {
groups: {}
}
});b除了b.user.groups没有任何其他属性,所有其他属性都会被删除。是否有任何ES6方法仅用Object.assign更改嵌套属性,而不松开其他属性?
发布于 2017-01-11 10:58:33
经过一些尝试,我可以找到一个看起来不错的解决方案:
const b = Object.assign({}, a, {
user: {
...a.user,
groups: 'some changed value'
}
});为了使这个答案更完整,这里有一个小小的注解:
const b = Object.assign({}, a)本质上与以下内容相同:
const b = { ...a }因为它只是将a (...a)的所有属性复制到一个新对象中。因此,上面的内容可以写成:
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
}
}发布于 2019-09-24 23:36:43
下面是一个名为Object_assign的小函数(如果需要嵌套赋值,只需用_替换. )
该函数通过直接粘贴源值来设置所有目标值,或者在目标值和源值都是非null对象时再次递归调用null。
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))
发布于 2017-05-18 09:11:12
您专门要求在ES6中使用Object.assign,但也许其他人会更喜欢我的“一般”答案--您可以很容易地使用lodash,而且我个人认为这个解决方案更容易读懂。
import * as _ from 'lodash';
_.set(a, 'user.groups', newGroupsValue);它会变异物体。
https://stackoverflow.com/questions/41588068
复制相似问题