问题描述
我有一个JSON数据,我需要做类似group by的工作,我在这里问过这个问题,但是我没有得到满意的答复,所以这次我想更深入地解释.
首先,有人可以向我解释javascript中groupby
和orderby
之间的区别吗,就像在sql中一样,我们确实需要汇总函数才能使用group by
.但是我不想要聚合函数之类的东西.在这里,我提供了我想要的非常简单的JSON数据和输出示例.
所有作者姓名均应为sortby
字母数字顺序.
JSON数据:
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"
}
]
}
]
}
预期输出:
John
4 testgroup4 clinicalnote
RRP
1 testgroup1 clinicalnote
3 testgroup3 clinicaldocument
LKP
2 testgroup2 clinicalimage
任何想法/建议/方向/思想都会有很大帮助.
您可以使用 Underscore.js轻松地做到这一点:
_.chain(myObject.Apps[0].groups).sortBy("author").groupBy("author").value();
输出JSON对象:
{
"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"}]
}
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.
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"}]
}
这篇关于使用javascript/jquery对JSON数据进行分组/排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!