For the project I’m currently on we are doing an insane amount of ajax calls combined with a ton of canvas visualizations (graphs & maps).
I’m finding that performance is in jeopardy based on the size of the json files as well as the number of calls that are made, so I’m trying to figure out that’s the best way to approach this. All of my visualizations are plotted on 2 dimensions, ie: [longitude, latitude], [distance,time] etc.. So a lot of my json returns look like this
{
"data": [
[
1,
2
],
[
2,
2
],
[
3,
2
]
]
}
These arrays are easy to plot and require little adjustment to work with the graphing plugins, but I’d have to make lot of calls to populate every graph.
So one way to deal with this is to lightly modify and reuse json arrays that I get from the back end so that I can use them in multiple visualizations that are on the page. This involves a little more data fondling on my end to get everything to work and that’s where the .map() method comes in.
{
"data": [
{
"lat": 1222,
"long": 32323,
"distance": 12,
"time": 0.35
},
{
"lat": 22,
"long": 323,
"distance": 19,
"time": 0.45
}
]
}
What .map() does is take an array and then remap it into a new array. For distance, long I would take the json array above and change it to
var data =[];
data =$.map(json.data, function(n){
return n.distance;
});
Which should return a new array with [distance, distance, distance] point sets.
FUN FACT: There is a bug with $.map where it always flattens your array, making tuples impossible and making Sues pull their hair out.
The way I tackled this issue for a recent project was using $.each().
var longLat =[]
$.each(json, function(i, val){
longLat.push([json[i].long, json[i].lat]);
}
Which gave me longLat= [[long,lat],[long,lat],[long,lat]]
When I need to create a new array containing multiple arrays of point sets I use .push without an each instead.
IE- I want this:
{
"metric1": [
[
1,
2
],
[
3,
2
]
],
"metric2": [
[
"blue",
1
],
[
"green",
2
]
]
}
to become: data = [ [1,2],[3,2] ], [ ["blue",1], ["green",2] ] ];
Then I would write:
data =[];
data.push(json.metric1);
data.push(json.metric2);
This is helpful if you are making multiple calls for datasets and need to put each into the same array. I will eventually put visualizations up so this makes more sense.
My best friend on this project has been JSONlint, making sure that my json returns weren’t total crap. And often a ” or a } was missing in a 1200 line return, which would be impossible to find without it.