Composite Map Keys Bundle Multiple Fields
Map compares object keys by reference, so multi-field lookups need one keyOf helper turning tenant, user, and day into a stable string key.
Code
// Map 的键按引用相等比较:内容相同的两个对象是不同的键
const seen = new Map();
seen.set({ tenant: 'a', user: 7 }, 'first');
console.log('stored under original object:', seen.size);
console.log('lookup with equal-content object:', seen.get({ tenant: 'a', user: 7 }));
// 组合键的标准做法:一个 keyOf 助手把字段序列化成稳定字符串键
const keyOf = (tenant, user, day) => `${tenant}:${user}:${day}`;
const sessions = new Map();
sessions.set(keyOf('a', 7, '2026-11-15'), 3);
sessions.set(keyOf('a', 7, '2026-11-16'), 1);
sessions.set(keyOf('b', 7, '2026-11-15'), 9);
console.log('lookup a/7/15:', sessions.get(keyOf('a', 7, '2026-11-15')));
console.log('lookup b/7/15:', sessions.get(keyOf('b', 7, '2026-11-15')));
// 增删改查都走同一个 keyOf,避免各处手拼分隔符不一致
const k = keyOf('a', 7, '2026-11-15');
sessions.set(k, sessions.get(k) + 1);
console.log('incremented:', sessions.get(k), 'of', sessions.size, 'entries');Output
Captured from a sandboxed run of this snippet in the build pipeline.
stored under original object: 1
lookup with equal-content object: undefined
lookup a/7/15: 3
lookup b/7/15: 9
incremented: 4 of 3 entriesReference equality bites
Map compares object keys by reference. The demo stores an entry under one object literal and immediately fails to find it with a second literal of identical shape — lookup with equal-content object prints undefined while stored under original object prints 1.
The keyOf helper
keyOf(tenant, user, day) joins fields into a stable string, and every session lookup, write, and increment goes through it. The three seed entries (a/7 on two days, b/7 on one) are all fetched by rebuilding the same string.
Single point of truth
Because increments reuse keyOf too (sessions.set(k, sessions.get(k) + 1)), no call site can drift into a different separator or field order — the output incremented: 4 of 3 entries shows the update landing on the intended row.
Interactive Tools for This Topic
FAQ
- Why does Map fail to find an object stored with the same shape?
- Object keys are compared by reference, so two structurally equal literals are different keys; only the original reference retrieves the value.
- What does centralizing keyOf prevent?
- Scattered ad-hoc string joins with inconsistent separators or field orders; every read and write rebuilds the same key through one function.
Report a problem with this exampleOpens a pre-filled issue on GitHub.