多级索引映射通过Map嵌套实现,即Map的value为另一Map,形成“目录树”结构;需手动初始化各级子Map,或封装setNested等通用方法避免重复判断。

用 Map 实现多级索引映射,核心思路是让 Map 的值(value)本身也是 Map,逐层嵌套,形成类似“目录树”的结构。这不是 Map 的内置功能,而是通过手动构造嵌套 Map 来达成的灵活索引能力。
一、基础结构:Map 套 Map
一级键对应一个子 Map,子 Map 再存下一级键值对。例如按“年→月→订单ID”组织数据:
const ordersByYearMonth = new Map();
// 初始化 2024 年
if (!ordersByYearMonth.has('2024')) {
ordersByYearMonth.set('2024', new Map());
}
// 初始化 2024 年 05 月
const may2024 = ordersByYearMonth.get('2024');
if (!may2024.has('05')) {
may2024.set('05', new Map());
}
// 存入具体订单
may2024.get('05').set('ORD-001', { amount: 299, user: 'Alice' });
二、封装通用方法:避免重复判断
每次手动检查和创建嵌套 Map 很繁琐。可封装一个安全设值函数:
function setNested(map, keys, value) {
let current = map;
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (!(current instanceof Map)) break;
if (!current.has(key)) {
current.set(key, new Map());
}
current = current.get(key);
}
if (current instanceof Map) {
current.set(keys.at(-1), value);
}
}
<p>// 使用示例
setNested(ordersByYearMonth, ['2024', '05', 'ORD-002'], { amount: 150, user: 'Bob' });
三、查询与遍历:支持部分路径匹配
多级 Map 的优势在于可按前缀快速筛选。比如查所有 2024 年的订单,或所有 5 月的订单:
立即学习“Java免费学习笔记(深入)”;
- 查某年所有月数据:`ordersByYearMonth.get('2024')` 返回整个子 Map
- 查某年某月所有订单:`ordersByYearMonth.get('2024')?.get('05')`
-
遍历某年全部订单:
const yearMap = ordersByYearMonth.get('2024'); if (yearMap) { for (const [month, orderMap] of yearMap) { for (const [id, order] of orderMap) { console.log(`${month}/${id}:`, order); } } }
四、配合 Set 做去重归类(进阶用法)
若需记录“每个用户在哪些月份下单”,可用 Map + Set 组合:
const userMonths = new Map(); // user → Set of months
function recordUserMonth(user, year, month) {
const key = `${year}-${month}`;
if (!userMonths.has(user)) {
userMonths.set(user, new Set());
}
userMonths.get(user).add(key);
}
recordUserMonth('Alice', '2024', '05');
recordUserMonth('Alice', '2024', '06');
// Alice → Set {'2024-05', '2024-06'}
这种结构天然支持快速查“某用户参与的所有时间段”,也便于后续交集/并集运算。


















