javascript - how to transform/group this kind of raw json data into hierarchy strucutre -
i have set of room data in json, each room data includes site, building , floor resides in.
the data examples like
[ { 'site':'liverpool', 'building':'building a', 'floor':'0', 'room':'room a' }, { 'site':'liverpool', 'building':'building a', 'floor':'1', 'room':'room b' }, { 'site':'liverpool', 'building':'building b', 'floor':'0', 'room':'room a' } ............ ]
now using javascript break down data set hierarchy structure, such as
{ 'site':[ { 'name':'liverpool', 'buildings':[ { 'name':'building a', 'floors':[ { 'name':0, 'rooms':['room a', 'room b'] } ] } ] } ] }
for me, still hard transform raw data wanted structure, instruct me how it?
i have tried underscore, achieved 1 hierarchy.
var groups = _.groupby(data,function(room){ return (room.site+","+room.building+","+room.floor); })
assuming var data
json:
var sites = []; for(var i=0,l=data.length;i<l;i++) { var row = data[i]; var site = false; var building = false; var floor = false; // search existing site for(var j=0,k=sites.length;j<k;j++) { if(sites[j].name == row.site) { site = j; break; } } if(site === false) { site = sites.length; sites[site] = { name: row.site, buildings: [] }; } // search existing building for(var j=0,k=sites[site].buildings.length;j<k;j++) { if(sites[site].buildings[j].name == row.building) { building = j; break; } } if(building === false) { building = sites[site].buildings.length; sites[site].buildings[building] = { name: row.building, floors: [] }; } // search existing floor for(var j=0,k=sites[site].buildings[building].floors.length;j<k;j++) { if(sites[site].buildings[building].floors[j] == row.floor) { floor = j; break; } } if(floor === false) { floor = sites[site].buildings[building].floors.length; sites[site].buildings[building].floors[floor] = row.floor; } }
resulting structure:
var sites = [ { "name":"liverpool", "buildings":[ { "name":"building a", "floors":[ "0", "1" ] }, { "name":"building b", "floors":[ "0" ] } ] } ];
use it:
var liverpool = sites[0]; var building_b = liverpool.buildings[1];
there better ways of doing though.
Comments
Post a Comment