Query JavaScript Object group by

时光怂恿深爱的人放手 提交于 2020-01-03 03:14:05

问题


I have a JavaScript object like this:

[{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":4},{"a":2,"b":5}]

I want to group this object field 'a' and want something like this:

[{"a":1,"values":[{"a":1,"b":2},{"a":1,"b":3}]},{"a":2,"values":[{"a":2,"b":4},{"a":2,"b":5}]}]

I have a JavaScript array of more than few thousands elements. What is the most efficient way to achieve this?


回答1:


Underscore JS provides nice methods for structuring your models and grouping/filtering them.

http://underscorejs.org/#groupBy




回答2:


Try this code:

var data = [{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":4},{"a":2,"b":5}];

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

Here ARRAY(_) is a special aggregation function which saves current record(_) into the array with name values.

You can play with this example in jsFiddle.



来源:https://stackoverflow.com/questions/35405937/query-javascript-object-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!