Created
October 16, 2012 14:30
-
-
Save jussiry/3899605 to your computer and use it in GitHub Desktop.
Parse Kovalo API data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Retrieves data from Kovalo API and changes id references to object references. | |
*/ | |
$.get("http://kovalo-grape.herokuapp.com/deals/near?latitude=60&longitude=24&radius=60", function(res) { | |
var check_key, data_root_obj, iterator, key, model_name, non_data_root_child; | |
// set the location/name of root object where the data will be stored: | |
data_root_obj = window.Data = {}; | |
// helper(s) | |
check_key = function(key, key_ending) { | |
var model_name_length; | |
if ((model_name_length = key.search(RegExp("_" + key_ending + "$"))) !== -1) { | |
return key.slice(0, model_name_length); | |
} | |
return false; | |
}; | |
// add root data elements to main data object | |
for (key in res) { | |
var child = res[key] | |
if (model_name = check_key(key, "data")) { | |
data_root_obj[model_name] = child; | |
} | |
else if (typeof child is 'object' && child != null) { | |
data_root_obj[key] = child; | |
} | |
} | |
// iterator that goes through data and changes id's to object references | |
iterator = function(obj) { | |
var arr, child, i; | |
for (key in obj) { | |
child = obj[key]; | |
if (model_name = check_key(key, "id")) { | |
obj[model_name] = res[model_name + "_data"][child]; | |
delete obj[key]; | |
} else if (model_name = check_key(key, "ids")) { | |
arr = obj[model_name + "s"] = []; | |
for (var i=0; i<child.length; i++) { | |
arr.push(res[model_name+'_data'][child[i]]); | |
} | |
delete obj[key]; | |
} else { | |
if (typeof child === "object") { | |
iterator(child); | |
} | |
} | |
} | |
}; | |
iterator(data_root_obj); | |
// all done, show results: | |
console.log('data parsed:', data_root_obj); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment