我确实有两个对象包含密钥,比如
var a = {bar:[1,2], foo:[7,9]}
var b = {bar:[2,2], foo:[3,1]}我想知道休闲结果:
var c = {bar:[3,4], foo:[10,10]}我已经有了一个for逻辑,例如:
for (let key in b) {
if (a[key]) {
a[key][0] += b[key][0];
a[key][1] += b[key][1];
}
else a[key] = b[key];
}但我想以一种套路的方式来阐述这一逻辑。我该怎么做呢?
发布于 2019-02-04 21:04:25
您可以使用create函数来获取n对象,并使用休息参数将它们收集到数组中。现在,您可以将数组合并到铺展中以组合对象,并在定制器函数中使用Array.map()或lodash的_.map()和_.add()对数组中的项进行求和
const { mergeWith, isArray, map, add } = _
const fn = (...rest) => _.mergeWith({}, ...rest, (o = [], s) =>
map(s, (n, i) => add(n, o[i]))
)
const a = {bar:[1,2], foo:[7,9]}
const b = {bar:[2,2], foo:[3,1]}
const c = {bar:[3,2], foo:[5,6]}
const d = {bar:[4,2], foo:[5,4]}
const result = fn(a, b, c, d)
console.log(result)<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
还可以使用lodash/fp创建一个函数,将所有值与_.mergeAllWith()合并到多维数组中,然后使用_.zipAll()转换数组,并对每个数组进行求和:
const { rest, flow, mergeAllWith, isArray, head, mapValues, zipAll, map, sum } = _
const fn = rest(flow(
mergeAllWith((o, s) => [...isArray(head(o)) ? o : [o], s]), // combine to a multidimensional array
mapValues(flow(
zipAll,
map(sum)
)),
))
const a = {bar:[1,2], foo:[7,9]}
const b = {bar:[2,2], foo:[3,1]}
const c = {bar:[3,2], foo:[5,6]}
const d = {bar:[4,2], foo:[5,4]}
const result = fn(a, b, c, d)
console.log(result)<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
发布于 2019-02-04 21:35:54
您可以使用普通JavaScript和Object.entries、concat和reduce来完成这一任务。
const a = { bar: [1,2], foo: [7,9] };
const b = { bar: [2,2], foo: [3,1] };
const entries = Object.entries(a).concat(Object.entries(b));
const result = entries.reduce((accum, [key, val]) => {
accum[key] = accum[key] ? accum[key].map((x, i) => x + val[i]) : val;
return accum;
}, { });
console.log(result);
https://stackoverflow.com/questions/54522863
复制相似问题