linq.js groupby with Json

Raza picture Raza · Aug 6, 2013 · Viewed 8.6k times · Source

This is my Json Object in simplified form.

 var jsonObject =
    [
        {"City":"Monroe","Country":"USA","Latitude":47.8524,"Longitude":-121.98151},
        {"City":"Austin","Country":"USA","Latitude":30.40137,"Longitude":-97.73542},
        {"City":"Austin","Country":"USA","Latitude":30.32198,"Longitude":-97.70864}
    ]

I want to groupBy using City and get the count of records belonging to a specific city, The code that I've tried so far is

    var query2 = $.Enumerable.From(jsonObject)
.GroupBy(
function(record) {return record.City},

function(record) {
        return {City: record.City}
    },
function(rec) {
        return {City:rec}
    }
).ToArray();

I'm still not able to get what i'm doing wrong here. i'm new to linq.js...any help would be appretiated, or atleast point me at right direction.

Answer

Jeff Mercado picture Jeff Mercado · Dec 18, 2013

So you just wanted to get the count of cities? Try this instead:

var query = Enumerable.From(jsonObject)
    .GroupBy(
        "$.City",
        null,
        "{ City: $, Count: $$.Count() }") // $: Key, $$: Group
    .ToArray();