Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by/order by On JSON data using javascript/jquery

I have a JSON data and I need to do something like group by and i asked this question before here but i am not getting any satisfied answer so this time i would like to explain more in depth.

First, Can anybody explain me difference between groupby and orderby in javascript as in sql we do required aggregate function in order to use group by. But I don't want anything like aggregate function. Here I provide a very sample JSON data and Output that I was looking for.

All author names should be sortby alphanumeric order.

JSON data:

var myObject = {
    "Apps": [
        {
            "Name": "app1",
            "id": "1",
            "groups": [
                {
                    "id": "1",
                    "name": "test group 1",
                    "category": "clinical note",
                    "author": "RRP"
                }, {
                    "id": "2",
                    "name": "test group 2",
                    "category": "clinical image",
                    "author": "LKP"
                }, {
                    "id": "3",
                    "name": "test group 3",
                    "category": "clinical document",
                    "author": "RRP"
                }, {
                    "id": "4",
                    "name": "test group 4",
                    "category": "clinical note",
                    "author": "John"
                }
            ]
        }
    ]
}

Expected output:

John
  4 testgroup4 clinicalnote 
RRP
  1 testgroup1  clinicalnote
  3 testgroup3  clinicaldocument
LKP
  2 testgroup2 clinicalimage    

Any idea/suggestion/direction/thought would be great help.

like image 326
ravi Avatar asked Feb 25 '26 18:02

ravi


1 Answers

You can do that easily with Underscore.js:

_.chain(myObject.Apps[0].groups).sortBy("author").groupBy("author").value();

Outputs a JSON object:

{
 "John":[{"id":"4","name":"test group 4","category":"clinical note","author":"John"}],
 "LKP":[{"id":"2","name":"test group 2","category":"clinical image","author":"LKP"}],
 "RRP":[{"id":"1","name":"test group 1","category":"clinical note","author":"RRP"},{"id":"3","name":"test group 3","category":"clinical document","author":"RRP"}]
}
like image 50
Andrejs Avatar answered Feb 27 '26 07:02

Andrejs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!