如何将这种原始json数据转换/分组为层次结构

时间:2014-03-10 12:46:46

标签: javascript json

我在json中有一组房间数据,每个房间数据包括它所在的站点,建筑物和楼层。

数据示例如

[
{
  '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' 
}
............
]

现在我使用javascript将此数据集分解为层次结构,例如

{
    'site':[
        {
            'name':'liverpool',
            'buildings':[
                {
                    'name':'building a',
                    'floors':[
                     {
                         'name':0,
                         'rooms':['room a', 'room b']
                     }
                    ]
                }
            ]
        }
    ]
} 

对我来说,将原始数据转换为有用结构仍然非常困难,有人可以指导我如何做到这一点吗?

我尝试使用下划线,但只能使用一个层次结构。

 var groups = _.groupBy(data,function(room){
                return (room.site+","+room.building+","+room.floor);        
            }) 

1 个答案:

答案 0 :(得分:1)

假设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 for 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 for 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 for 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;
    }
}

产生的结构:

var sites = [
    {
        "name":"liverpool",
        "buildings":[
            {
                "name":"building a",
                "floors":[
                    "0",
                    "1"
                ]
            },
            {
                "name":"building b",
                "floors":[
                    "0"
                ]
            }
        ]
    }
];

使用它:

var liverpool = sites[0];
var building_b = liverpool.buildings[1];

虽然可能有更好的方法。