【发布时间】:2019-05-11 09:07:10
【问题描述】:
我有两个这样的对象:
const object1 = {first: [{a: 0, b:3}], second: [{a: 1, b:2}], third: [{a: 3, b:2}]}
const object2 = {first: [{a: 1, b:0}], second: [{a: 10, b:0}], third: [{a: 2, b:3}]}
我想要这两个对象的总和:
const res = {first: [{a: 1, b:3}], second: [{a: 11, b:2}], third: [{a: 5, b:5}]}
我尝试以这种方式使用 Lodash 的 mergeWith:
const res = mergeWith({}, object1, object2, add)
但我明白了:
{first: NaN, second: NaN, third: NaN}
如何将 mergeWith 用于嵌套对象?
【问题讨论】:
-
add函数在做什么? -
是Lodash的添加功能
-
啊,我明白了。我没有意识到您正在单独导入这些功能。在这种情况下,它将无法工作,因为它会尝试将 array 添加到另一个数组中,这会导致
NaN,如您所见。 -
@vlaz 好的,有什么解决方法吗?
-
数组中是否总是只有一个对象?我的意思是
first: [{a: 0, b:3}]- 如果数组中有两个条目,那么合并逻辑可能会更复杂。或者可能不是 - 如果您希望合并匹配的索引。
标签: javascript merge lodash