I recently shared how you can merge object properties with the spread operator but this method has one big limitation: the spread operator merge isn't a "deep" merge, meaning merges are recursive. Moreover nested object properties aren't merged -- the last value specified in the merge replaces the last, even when there are other properties that should exist.
我最近分享了如何使用传播运算符合并对象属性,但是这种方法有一个很大的局限性:传播运算符合并不是“深度”合并,这意味着合并是递归的。 而且,嵌套对象的属性不会合并-合并中指定的最后一个值会替换最后一个,即使应该存在其他属性也是如此。
const defaultPerson = {
name: 'Anon',
gender: 'Female',
hair: {
color: 'brown',
cut: 'long'
},
eyes: 'blue',
family: ['mom', 'dad']
};
const me = {
name: 'David Walsh',
gender: 'Male',
hair: {
cut: 'short'
},
family: ['wife', 'kids', 'dog']
};
const summary = {...defaultPerson, ...me};
/*
{
"name":"David Walsh",
"gender":"Male",
"hair":{
"cut":"short"
},
"eyes":"blue",
"family":[
"wife",
"kids",
"dog"
]
}
*/
In the sample above, you'll notice that the hair
object's color
is gone instead of m