user1375353
user1375353

Reputation: 13

How to Calculate the sum in nested JSON using Underscore JS

I am getting as a JSON response from an API. The main goal I need to achieve is to calculate the sum of all the #'s in the objects. I would like to use underscore to do this for simplicity, but I cannot understand how I would achieve this.

This is my response.

 [{
    "data": {          
            "row": [{
                "col": ["2015-02-10", "item1", "1"]
            }, {
                "col": ["2015-02-11", "item2", "1504"]
            }, {
                "col": ["2015-02-12", "item3", "66"]
            }, {
                "col": ["2015-02-13", "item4", "336"]
            }, {
                "col": ["2015-02-14", "item5", "19"]
            }, {
                "col": ["2015-02-15", "item6", "210"]
            }, {
                "col": ["2015-02-16", "item7", "36"]
            }, {
                "col": ["2015-02-17", "item8", "1742"]
            }, {
                "col": ["2015-02-18", "imem9", "61"]
            }, {
                "col": ["2015-02-19", "item10", "22"]
            }]
        }
    }
}]

Upvotes: 1

Views: 994

Answers (2)

joews
joews

Reputation: 30330

You don't need underscore for this - you can do it with Array.prototype.reduce, which is one of the _-style functions that JavaScript provides:

var total = input[0].data.row.reduce(function (sum, element) {
    return sum + (+element.col[2]) 
}, 0);

I've assumed that the numbers you want to sum are the third element in each col array, e.g. 22 for ["2015-02-19", "item10", "22"].

Upvotes: 1

Eugene J. Lee
Eugene J. Lee

Reputation: 580

If you really want to use Underscore for this, just group/reduce it down and sum it up.

var groups = _(items).groupBy(function(o) {
    return o.col[1];
});

var sum2 = {};
_.each(groups, function(group, key) {
  sum2[key] = _.reduce(group, function(memo, item) {
    return memo + (parseInt(item.col[2]) || 0);
  }, 0);
});

Upvotes: 2

Related Questions