1

Below is the array that is generated from my json response

 [
        {
    "id": "name1",
    "c1": "10",
    "c2": "20",
    "c3": "30",
    "c4": "40"
        },
    {
    "id": "name2",
    "c1": "20",
    "c2": "40",
    "c3": "25",
    "c4": "38"
        }
    ]

I need to calculate the sum of the values of the fields except the first field, as the first that I get is a field name

Result array:

  [
    "c1": 30,
    "c2": 60,
    "c3": 55,
    "c4": 78
      ]
1

5 Answers 5

1

Using only ES6, you can do this with 2 Array#reduce loops:

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);

Or you can use lodash's _.mergeWith(), and _.omit() the 'id' from the result:

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to change the output to the below format [ {"c1": 30}, {"c2": 60}, { "c3": 55}, {"c4": 78} ]
You can use lodash's _.map() on the result -> _.map(result, (v, k) => ({ [k]: v }));. I've added an example to the 2nd answer.
0

ES6 syntax:

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)

Comments

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));

Comments

0

Assuming you are looking for a resulting object, and not an array of objects:

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);

Comments

0

Using lodash try

sum

_.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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.