JavaScript SUM and GROUP BY of JSON data
This is my first attempt at doing JavaScript with some JSON data objects and need some advice on the proper way to attain my goal. Some server-side code actually generates a JSON formatted string that I have to work with and assign it to a string:
But the end-result I have to work with after the server substitutes its data (without the \r\n, of course):
And then I can change it to an object to work with.
This allows me to access the data individual rows of data, but I need to sum, group by, and order the values. I need to the equivalent of an SQL statement like this:
My desired output would be an object like this that I can further process:
...but i don't know where to start. I could loop through all the category values and find the unique categories first, then loop again and sum the hits and bytes, then again to sort, but it seems there has got to be an easier way. prototype.js (1.7) is already included on the client page, but I could add Underscore, jQuery, or some other small library if I had to. I just don't know what would be best, easiest, smallest with the least amount of code to process the query. Any suggestions? javascript json group-by sum
|
|||||||||
|
4 Answers
active oldest votes12 |
You can use the native functions
If you're supporting older implementations, you'll need to use a shim for
|
||||||||||||||||
|
3 |
If you go the LINQ.js route, you can do it like this:
Working demo with Stack Snippets:
Also, you can find more info on linqjs group by with a sum
|
||
add a comment |
1 |
Given the dataString above, the below code seems to work. It goes through each object; if the category exists in the This solution makes use of underscore.js and jQuery Here's a jsfiddle demo: http://jsfiddle.net/R3p4c/2/
|
||||
|
0 |
|