Skip to content

How to add own keys for grouped output

agershun edited this page Dec 28, 2014 · 1 revision

How to add own keys for grouped output?

Source: StackOverflow.com

The raw data returned is this:

    [
        {
            "name": "jim",
            "color": "blue",
            "age": "22"
        },
        {
            "name": "Sam",
            "color": "blue",
            "age": "33"
        },
        {
            "name": "eddie",
            "color": "green",
            "age": "77"
        }
    ]

I want the "group by" function to return an object that looks like this:

    [
        {
            color: "blue",
            users: [
                {
                    "name": "jim",
                    "color": "blue",
                    "age": "22"
                },
                {
                    "name": "Sam",
                    "color": "blue",
                    "age": "33"
                }
            ]
        },
        {
            color: "green",
            users: [
                {
                    "name": "eddie",
                    "color": "green",
                    "age": "77"
                }
            ]
        }
    ]

Answer

    var res = alasql('SELECT color, ARRAY(_) AS users FROM ? GROUP BY color',[data]);

Try this example in jsFiddle

Clone this wiki locally