Skip to content

Instantly share code, notes, and snippets.

@nahakyuu
Created September 8, 2016 09:53
Show Gist options
  • Save nahakyuu/bb5d5120141cb8fbedb1f58e9d1d1ce2 to your computer and use it in GitHub Desktop.
Save nahakyuu/bb5d5120141cb8fbedb1f58e9d1d1ce2 to your computer and use it in GitHub Desktop.
数据格式转换
interface Room {
name: string;
floor: string;
unit: string;
buildId: string;
}
interface Build {
buildId: string;
unit: Array<Unit>;
}
interface Unit {
id: string;
floor: Array<Floor>
}
interface Floor {
id: string;
room: Array<Room>
}
let data: Array<Room> = [
{
"name": "101",//房间号,表示1楼1号房
"floor": "1-1",//楼层号,表示1单元1楼
"unit": "1",//单元号,表示1单元
"buildId": "1#"//楼栋id,表示1号楼
},
{
"name": "102",
"floor": "1-1",
"unit": "1",
"buildId": "1#"
},
{
"name": "201",
"floor": "1-2",
"unit": "1",
"buildId": "1#"
},
{
"name": "202", //房间号,表示2楼2号房
"floor": "1-2",//楼层号,表示1单元2楼
"unit": "1",
"buildId": "1#"
},
{
"name": "101",//房间号,表示1楼1号房
"floor": "2-1",//楼层号,表示2单元1楼
"unit": "2",//单元号,表示2单元
"buildId": "1#"
},
{
"name": "101",//房间号,表示2楼1号房
"floor": "2-2",//楼层号,表示2单元2楼
"unit": "2",//单元号,表示2单元
"buildId": "1#"
}];
let result = data.reduce((result, room) => {
let unit = result.unit.find(unit => unit.id == room.unit);
if (unit) {
let floor = unit.floor.find(floor => floor.id == room.floor);
if (floor) {
floor.room.push(room);
} else {
let roomList: Array<Room> = [];
roomList.push(room);
let floor: Floor = { id: room.floor, room: roomList };
unit.floor.push(floor);
}
} else {
let roomList: Array<Room> = [];
roomList.push(room);
let floorList: Array<Floor> = [];
floorList.push({ id: room.floor, room: roomList });
let unit = { id: room.unit, floor: floorList };
result.unit.push(unit);
}
return result;
}, { buildId: '1#', unit: [] } as Build);
@nahakyuu
Copy link
Author

nahakyuu commented Sep 8, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment