现在有
let arr = [
{age: 10, price: 20},
{age: 20, price: 30},
{age: 30, price: 30}
]
然后对age和price求和。
想得到
{age: 60, price: 80}
这样的对象。
如果age和price属性名动态的又该如何写呢??
现在有
let arr = [
{age: 10, price: 20},
{age: 20, price: 30},
{age: 30, price: 30}
]
然后对age和price求和。
想得到
{age: 60, price: 80}
这样的对象。
如果age和price属性名动态的又该如何写呢??
const sum = (...columns) => arr => arr.reduce((a, b) => columns.reduce((c, d) => ({...c, [d]: a[d] + b[d]}), {}))
function getSum(key1, key2, ary) {
return ary.reduce((pre, next) => {
pre[key1] = (pre[key1] || 0) + (next[key1] || 0)
pre[key2] = (pre[key2] || 0) + (next[key2] || 0)
return pre
}, {})
}
let res = getSum('age', 'price', arr)
function sum(arr) {
return arr.reduce((res, v) => {
return Object.keys(v).reduce((res, k) => {
res[k] = (res[k] || 0) + v[k];
return res;
}, res);
}, {})
}
const merge = data => {
return data.reduce((acc, cur) => {
const obj = {...acc}
for(let attr in cur) {
if(cur.hasOwnProperty(attr)) {
if(obj[attr]) {
obj[attr] += cur[attr]
}else {
obj[attr] = cur[attr]
}
}
}
return obj
}, {})
}
merge(arr)
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决