如何在Angular中实现重复键的键值对数据存储?
Angular 存储重复键键值对的实现方案
JavaScript/TypeScript 原生的Map结构强制键唯一,同键赋值会覆盖旧值,要实现一对多的键值存储,可以使用以下几种兼容Angular的方案:
方案1:值类型为数组的Map(最常用)
直接将Map的泛型值定义为数组类型,同一个键下的所有值存入同一个数组即可,不会出现覆盖问题。
示例代码:
// 定义Map,值为number数组 commentMap = new Map<number, number[]>(); // 封装添加元素的方法 addComment(key: number, value: number) { // 如果键不存在,先初始化空数组 if (!this.commentMap.has(key)) { this.commentMap.set(key, []); } // 往对应键的数组追加值 this.commentMap.get(key)?.push(value); } // 调用添加数据 this.addComment(101,999); this.addComment(101,989); this.addComment(101,987); this.addComment(102,888); this.addComment(102,887);
读取示例:
// 获取101对应的所有值,输出 [999, 989, 987] console.log(this.commentMap.get(101)); // 遍历输出所有键值对 this.commentMap.forEach((values, key) => { values.forEach(val => { console.log(`${key} , ${val}`); }) })
方案2:对象数组
如果你的使用场景以全量遍历为主,不需要频繁按键查询,也可以直接存储结构为{key: number, value: number}的数组:
commentList: {key: number, value: number}[] = []; // 添加元素 this.commentList.push({key: 101, value: 999}); this.commentList.push({key: 101, value: 989}); // 后续添加逻辑同理
方案3:封装自定义Multimap
如果需要更完善的增删改查API,可以自行封装一个Multimap类复用:
class Multimap<K, V> { private map = new Map<K, V[]>(); set(key: K, value: V) { if (!this.map.has(key)) { this.map.set(key, []); } this.map.get(key)!.push(value); } get(key: K): V[] | undefined { return this.map.get(key); } has(key: K): boolean { return this.map.has(key); } delete(key: K, value?: V): boolean { if (!value) return this.map.delete(key); const values = this.map.get(key); if (!values) return false; const index = values.indexOf(value); if (index === -1) return false; values.splice(index, 1); if (values.length === 0) this.map.delete(key); return true; } } // 使用示例 const commentMap = new Multimap<number, number>(); commentMap.set(101, 999); commentMap.set(101, 989);
以上方案均为原生TypeScript/JavaScript支持的实现,无需引入额外依赖,可以直接在Angular的组件、服务中使用。
内容的提问来源于stack exchange,提问作者angular_code
相关产品推荐
相关产品推荐

