JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<pre id="output"></pre>
JavaScript
//------------- Function to print -------------------------//
function out()
{
var args = Array.prototype.slice.call(arguments, 0);
document.getElementById('output').innerHTML += args.join(" ") + "\n";
}
//--------------------------------------------------------//
var apiKey = 'INSERT API KEY HERE';
/**
* Map dynamic keys to an attribute 'ID' of enclosing object.
*
* @param json JSON response from the Torn API
* @return Returns a mapped JSON if needed otherwise returns the input JSON.
*/
function mapIDs(json) {
var mappedJson = {};
var types = [
'bazaar',
'itemmarket',
'pointsmarket',
'events',
'messages',
'attacks',
'stocks',
'properties',
'mainnews',
'mainnewsfull',
'attacknews',
'attacknewsfull',
'armorynews',
'armorynewsfull',
'donationnews',
'donationnewsfull',
'crimes',
'attacks',
'attacksfull',
'company_employees'
];
var found = false;
for (t = 0; t < types.length; t++) {
var type = types[t];
if (json.hasOwnProperty(type)) {
found = true;
var obj = json[type];
mappedJson[type] = [];
for (var key in obj) {
var mappedInnerJson = {};
mappedInnerJson.id = parseInt(key);
var innerObj = obj[key];
for (var innerKey in innerObj) {
mappedInnerJson[innerKey] = innerObj[innerKey];
}
mappedJson[type].push(mappedInnerJson);
}
}
}
// If any mapping has been done return the mapped json object.
if (found) return mappedJson;
else return json;
}
function ajaxApiGet(id, type, selections, apiKey) {
$.ajax({
url : '//api.torn.com/' + type + '/' + id,
type : 'GET',
data : {
selections : selections,
key : apiKey,
},
success : function (json) {
var mappedJson = mapIDs(json);
out(JSON.stringify(mappedJson, null, 2));
}
});
}
ajaxApiGet(1, 'market', 'pointsmarket,itemmarket,bazaar', apiKey);