Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linqjs group by with a sum

This might seems like an easy question but I'm struggling with the linqjs syntax.

Given the following basic JSON:

{
        "DateEvent": "2013-04-23 14:00:00Z",
        "DateRecord": "2013-04-23 14:00:00Z",
        "Amount": -9500,
        "Type": {
            "Description": "Capital"
        },
        "Currency": {
            "ID": "USD",
        }
}

Using linqjs how can I return the total for each currency?

Enumerable.From(data)
    .GroupBy("{ currency: $.Currency.ID }", null, 
        function (key, g) {
            var result = {
                    currency: key.currency,
                    total: g.Sum($.Amount)
                }});

The code above doesn't work.

like image 643
paligap Avatar asked Jul 24 '13 01:07

paligap


2 Answers

You almost had it. Your key selector in your GroupBy and Sum is incorrect. Also the key selector needs to be a string. Try the following:

var result = Enumerable.from(data).groupBy("$.Currency.ID", null,
    function (key, g) {
        var result = {
            currency: key,
            total: g.sum("$.Amount")
        }
        return result;
    }).ToArray();
like image 154
Rei Mavronicolas Avatar answered Sep 30 '22 07:09

Rei Mavronicolas


I am the author of the open-source project http://www.jinqJs.com

You could easily do it by executing:

new jinqJs().from(data).groupBy('Currency').sum('Amount').select();
like image 35
NYTom Avatar answered Sep 30 '22 08:09

NYTom