我有两个这样的对象:
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与嵌套对象一起使用?
最佳答案
执行 mergeWith
时,您需要传递一个定制器。然后,Lodash进行值的递归合并。
诀窍是,如果您的定制程序返回undefined
,那么merge
用于组合值。但是,由于add
为不兼容的值返回NaN
,因此将使用该值-因此,如果您仅具有一个类似于add
的功能,但返回undefined
而不是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;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
另一种简短的表达方式是使用
defaultTo
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);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>