问题
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