JSFiddle - React, Tailwind, and code Playground
by tivie
HTML
<script id="myJson" type="application/json">
{
"stuff":[
{
"State_Code":"01",
"County_Code":"000",
"State_Abbrv":"AL",
"County_Name":"ALABAMA",
"DATA":"12345"
},
{
"State_Code":"01",
"County_Code":"001",
"State_Abbrv":"AL",
"County_Name":"AUTAUGA COUNTY",
"DATA":"123"
},
{
"State_Code":"01",
"County_Code":"003",
"State_Abbrv":"AL",
"County_Name":"BALDWIN COUNTY",
"DATA":"321"
},
{
"State_Code":"02",
"County_Code":"000",
"State_Abbrv":"AK",
"County_Name":"ALASKA",
"DATA":"98765"
},
{
"State_Code":"02",
"County_Code":"013",
"State_Abbrv":"AK",
"County_Name":"ALEUTIANS EAST BOROU",
"DATA":"456"
}
]
}
</script>
JavaScript
var statesObj = $.parseJSON(document.getElementById('myJson').innerHTML).stuff,
finalObj = {
USA : {
name: "USA",
children: []
}
};
for (var st = 0; st < statesObj.length; ++st) {
// First the states
if( statesObj[st].County_Code === "000") {
var newState = {
name: statesObj[st].County_Name,
abbrv: statesObj[st].State_Abbrv,
children: []
};
finalObj.USA.children.push(newState);
}
}
for (var st = 0; st < statesObj.length; ++st) {
// Now the rest
if( statesObj[st].County_Code !== "000") {
var newChild = {
name: statesObj[st].County_Name,
data: statesObj[st].DATA
};
for (var sub in finalObj.USA.children) {
if (finalObj.USA.children.hasOwnProperty(sub) &&
finalObj.USA.children[sub].abbrv === statesObj[st].State_Abbrv) {
finalObj.USA.children[sub].children.push(newChild);
break;
}
}
}
}
var finalJson = JSON.stringify(finalObj);
console.log(finalJson);