我有两个这样的对象:
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与嵌套对象一起使用?
答案 0 :(得分:1)
进行mergeWith
时,您需要传递一个定制器。然后,Lodash进行值的递归合并。
诀窍是,如果您的定制器返回undefined
,则使用merge
来组合值。但是,由于add
对于不兼容的值返回NaN
,因此将使用该值-因此,如果您仅具有一个与add
类似的函数,但返回的是undefined
而不是{{ 1}},那么NaN
将为您完成所有繁重的工作:
mergeWith
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 = _.mergeWith({}, object1, object2, customizer)
console.log(res);
function customizer(a, b) {
// you can still use add
const result = _.add(a, b);
// ignore NaN values and return undefined instead
if (_.isNaN(result)) {
return;
}
//only combine values that can be combined
return result;
}
另一种简短的表达方式是使用defaultTo
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
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 customizer = (a, b) => _.defaultTo(_.add(a, b), undefined)
const res = _.mergeWith({}, object1, object2, customizer)
console.log(res);
答案 1 :(得分:0)
定义如何添加对象的窍门:
const res = mergeWith(object1, object2, (objValue, srcValue) =>
[{
a: objValue[0].a + srcValue[0].a,
b: objValue[0].b + srcValue[0].b
}]
)