I develop a tchat in ajax and needed to save some space in the json
that comes back from the server, so instead of sending messages like
[Name:Value,Name:Value,......] which can get quite big if you return a
collection of 50-100 users with lots of info, i wanted something more
like [Value,Value,Value] but still be able to acess the object in a
normal way, and came up with this:
<!-- start code -->
//Simulate the json object
var ref_data = {value:[["Marcel",31,"Paris"],["Karl",
15,"Germany"]],ref:["Name","Age","City"]};
// Function to merge a value collection and a ref
// table back to a name/value collection
function ObjMerge(obj){
var out = [];
$.each(obj.value, function(i, o){
out[i] = [];
$.each(obj.ref, function(ii, oo){
out[i][oo] = o[ii];
});
});
return out;
}
// Merge the json response
var users = ObjMerge(ref_data);
// test it out!
// could use this too: users[xx].Field
$.each(users, function(i,n){
alert("Name: "+n.Name+", Age: "+n.Age+", City: "+n.City);
});
<!-- end code -->
I'm no pro in javascript so if anyone sees something that could go
wrong or be done better, feel free to suggest !
Thank's,
Robert