JSFiddle - React, Tailwind, and code Playground
JavaScript
// this way, data is already an object
var data = { "medals": {
"Archery":[{
"stats_id": "83",
"gold": "0",
"silver": "0",
"bronze": "0",
"total": "0"
}],
"Track & Field":[{
"stats_id": "83",
"gold": "0",
"silver": "1",
"bronze": "0",
"total": "1"
}] // more data here...
}};
// if data comes this way, it need to be parsed
var dataStr = "{ \"medals\": {" +
" \"Archery\":[{" +
" \"stats_id\": \"83\"," +
" \"gold\": \"0\"," +
" \"silver\": \"0\"," +
" \"bronze\": \"0\"," +
" \"total\": \"0\"" +
" }]," +
" \"Track & Field\":[{" +
" \"stats_id\": \"83\"," +
" \"gold\": \"0\"," +
" \"silver\": \"1\"," +
" \"bronze\": \"0\"," +
" \"total\": \"1\"" +
" }]" + // more data here...
"}}";
console.log( data );
var obj = $.parseJSON( dataStr );
console.log( obj );
traverseObj(obj);
// traverses the object to see all its properties
function traverseObj( data ) {
for ( var key in data ) {
var value = data[key];
if ( $.isPlainObject( value ) ) {
console.log( "**key: " + key );
traverseObj( value );
} else if ( $.isArray( value ) ) {
console.log( "key: " + key );
var values = "";
for ( var i = 0; i < value.length; i++ ) {
var currValue = value[i];
if ( $.isPlainObject( currValue ) ) {
traverseObj(currValue);
} else {
values += currValue + ", ";
}
if ( values != "" ) {
console.log( " - value: " + value );
}
}
} else {
console.log( "key: " + key + " - value: " + value );
}
}
}