gpt4 book ai didi

javascript - 如何使用函数式编程遍历键映射并与另一个键映射进行比较

转载 作者:行者123 更新时间:2023-11-29 17:52:43 25 4
gpt4 key购买 nike

我有 2 个关键映射,我想对其进行迭代。如果 key 相同,那么我想使用 _.assign() 来覆盖值。例如:

var keyMap1 = {
1: {
id: 1,
name: 'egg'
},
2: {
id: 2,
name: 'bacon'
}
};

var keyMap2 = {
1: {
id: 1,
quantity: 3
},
2: {
id: 2,
quantity: 2
}
};

// something like this, preferably with lodash
var result = _.compareKeys(override, keyMap1, keyMap2);

function override(obj1, obj2){
return _.assign(obj1, obj2)
}
console.log(result);
// => { 1: { id: 1, name: 'egg', quantity: 3 }, 2: { id: 2, name: 'bacon', quantity: 2 } };

最佳答案

如果我理解你的要求,你能不能只使用 _.merge 来进行比较和赋值?

var keyMap1 = {
1: {
id: 1,
name: 'egg'
},
2: {
id: 2,
name: 'bacon'
}
};

var keyMap2 = {
1: {
id: 1,
quantity: 3
},
2: {
id: 2,
quantity: 2
}
};

var result = _.merge({}, keyMap1, keyMap2);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

关于javascript - 如何使用函数式编程遍历键映射并与另一个键映射进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41787170/

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