gpt4 book ai didi

javascript - 将 Lodash 的 mergeWith 与嵌套对象一起使用

转载 作者:行者123 更新时间:2023-11-30 14:15:11 25 4
gpt4 key购买 nike

我有两个这样的对象:

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/lodash@4.17.11/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/lodash@4.17.11/lodash.min.js"></script>

关于javascript - 将 Lodash 的 mergeWith 与嵌套对象一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53706122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com