下面是从我的json响应中生成的数组
[
{
"id": "name1",
"c1": "10",
"c2": "20",
"c3": "30",
"c4": "40"
},
{
"id": "name2",
"c1": "20",
"c2": "40",
"c3": "25",
"c4": "38"
}
]
我需要计算除第一个字段以外的字段值的总和,因为我得到的第一个是字段名称
结果数组:
[
"c1": 30,
"c2": 60,
"c3": 55,
"c4": 78
]
答案 0 :(得分:1)
仅使用ES6,您可以使用2个Array#reduce
循环执行此操作:
const data = [{"id":"name1","c1":"10","c2":"20","c3":"30","c4":"40"},{"id":"name2","c1":"20","c2":"40","c3":"25","c4":"38"}];
const result = data.reduce((sums, obj) => Object.keys(obj).reduce((s, k) => {
k === 'id' || (s[k] = (s[k] || 0) + +obj[k]);
return s;
}, sums), {});
console.log(result);

或者您可以使用lodash' _.mergeWith()
和_.omit()
' id'从结果:
const data = [{"id":"name1","c1":"10","c2":"20","c3":"30","c4":"40"},{"id":"name2","c1":"20","c2":"40","c3":"25","c4":"38"}];
const result = _.omit(_.mergeWith({}, ...data, (objValue = 0, srcValue = 0) => +objValue + +srcValue), 'id');
console.log(result);
console.log(_.map(result, (v, k) => ({ [k]: v }))); // or as a series of objects

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
答案 1 :(得分:0)
ES6语法:
const a = [
{
"id": "name1",
"c1": "10",
"c2": "20",
"c3": "30",
"c4": "40"
},
{
"id": "name2",
"c1": "20",
"c2": "40",
"c3": "25",
"c4": "38"
}
];
const b = a.reduce((a, v) => {
Object.keys(v).filter(e => e.startsWith('c')).forEach(k => a[k] = (a[k]) ? a[k] + +v[k] : +v[k]);
return a;
}, {});
console.log(b)
&#13;
答案 2 :(得分:0)
var values = [{
"id": "name1",
"c1": "10",
"c2": "20",
"c3": "30",
"c4": "40"
},
{
"id": "name2",
"c1": "20",
"c2": "40",
"c3": "25",
"c4": "38"
}
];
var results = {
"id": "totals",
"c1": 0,
"c2": 0,
"c3": 0,
"c4": 0
}
values.forEach(function(item) {
results.c1 += Number(item.c1);
results.c2 += Number(item.c2);
results.c3 += Number(item.c3);
results.c4 += Number(item.c4);
});
console.log(JSON.stringify(results));
答案 3 :(得分:0)
假设您正在寻找一个结果对象,而不是一个对象数组:
var srcObj = [{
"id": "name1",
"c1": "10",
"c2": "20",
"c3": "30",
"c4": "40"
},
{
"id": "name2",
"c1": "20",
"c2": "40",
"c3": "25",
"c4": "38"
}
];
var destObj = {};
srcObj.map((itm) => {
Object.keys(itm).forEach(function (key) {
if(key == 'id'){return;}
if(!destObj[key]){
destObj[key] = 0;
}
destObj[key] += parseInt(itm[key]);
});
});
console.log(destObj);
答案 4 :(得分:0)
使用lodash尝试
和
_.sum([4, 2, 8, 6]);
// => 20
sumby
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
_.sumBy(objects, function(o) { return o.n; });
// => 20
// The `_.property` iteratee shorthand.
_.sumBy(objects, 'n');
// => 20