如何从多维数组筛选数据并整理为层级化多维数组
如何从多维数组中筛选并整理Station、Room、Bed层级结构数据?
问题描述
我需要从一个多维数组中筛选出所有Station、Room和Bed数据,数组的每个元素对应一种类型(比如元素1是Station,元素2是Bed等),最终要整理成Station包含多个Room,每个Room包含多个Bed的层级结构(示例结构如下),试了多种方法都没做出来,求可行的实现方案。
目标结构示例:
[ [ "id" => 1234, "name" => "UB", "rooms" => [ [ "id" => 1234, "name" => "01", "beds" => [ ["id" => 1234, "name" => "09"] ] ], [ "id" => 1235, "name" => "02", "beds" => [ ["id" => 1234, "name" => "09"] ] ] ] ], [ "id" => 5678, "name" => "LB", "rooms" => [ [ "id" => 5678, "name" => "01", "beds" => [ ["id" => 1234, "name" => "09"], ["id" => 12345, "name" => "092"] ] ] ] ] ]
解决方案(以JavaScript为例)
假设原始数组每个元素包含type(取值为"station"/"room"/"bed")、id、name,以及parentId(Room的parentId对应所属Station的id,Bed的parentId对应所属Room的id),可以按以下步骤实现:
- 分类存储数据:先把三种类型的数据分别存入对象,方便通过id快速查找
- 关联Bed到Room:遍历所有Bed,把它们添加到对应Room的
beds数组中 - 关联Room到Station:遍历所有Room,把它们添加到对应Station的
rooms数组中 - 提取最终结构:把所有Station整理成数组,就是目标结构
代码示例:
// 原始数据示例 const rawData = [ { type: 'station', id: 1234, name: 'UB' }, { type: 'station', id: 5678, name: 'LB' }, { type: 'room', id: 1234, name: '01', parentId: 1234 }, { type: 'room', id: 1235, name: '02', parentId: 1234 }, { type: 'room', id: 5678, name: '01', parentId: 5678 }, { type: 'bed', id: 1234, name: '09', parentId: 1234 }, { type: 'bed', id: 12345, name: '092', parentId: 5678 }, ]; // 1. 分类存储 const stations = {}; const rooms = {}; const beds = {}; rawData.forEach(item => { switch(item.type) { case 'station': stations[item.id] = { ...item, rooms: [] }; break; case 'room': rooms[item.id] = { ...item, beds: [] }; break; case 'bed': beds[item.id] = item; break; } }); // 2. 关联Bed到Room Object.values(beds).forEach(bed => { if (rooms[bed.parentId]) { rooms[bed.parentId].beds.push(bed); } }); // 3. 关联Room到Station Object.values(rooms).forEach(room => { if (stations[room.parentId]) { stations[room.parentId].rooms.push(room); } }); // 4. 提取最终结构 const result = Object.values(stations); console.log(result);
关键说明
- 如果原始数据没有
parentId,而是通过其他方式关联(比如层级索引),只需要调整关联逻辑即可,核心思路都是先分类,再从最底层(Bed)往上关联到父级(Room),再关联到顶层(Station) - 用对象存储是为了O(1)的查找效率,比每次遍历数组查找父级性能更高,数据量大的时候优势明显
内容的提问来源于stack exchange,提问作者user22114465
相关产品推荐
相关产品推荐

