Angular TS 12中无表头CSV转对象数组实现数值匹配查询
Angular TS 12 无表头CSV匹配查询实现方案
实现思路
直接将CSV内容转换为Map<number, string>结构,查询时时间复杂度为O(1),比对象数组遍历匹配效率更高,完全适配按key查value的需求。
完整代码实现
首先在组件类中声明存储映射关系的属性:
// 组件类内部属性,存储CSV映射关系 private mappingMap = new Map<number, string>();
改造CSV读取处理方法:
fetchData() { fetch('../../../assets/static/mapping.csv') .then(response => response.text()) .then(data => { // 逐行拆分CSV内容 const rows = data.split('\n'); rows.forEach(row => { // 过滤空行 if (!row.trim()) return; // 拆分每行的两个字段 const [keyStr, valueStr] = row.split(','); // 处理字段格式:key转数字,value去除前后引号和空格 const key = parseInt(keyStr.trim(), 10); const value = valueStr.trim().replace(/^"|"$/g, ''); // 过滤非法数值后存入Map if (!isNaN(key)) { this.mappingMap.set(key, value); } }); }); }
编写查询调用方法:
// 输入查询数值,返回对应映射值,无匹配时返回undefined getMappingValue(input: number): string | undefined { return this.mappingMap.get(input); }
可选:转换为对象数组的实现
如果有遍历全量数据的需求,可以按以下方式转换为对象数组:
// 组件类内部属性 private mappingList: Array<{id: number, code: string}> = []; // fetchData内的处理逻辑替换为: const rows = data.split('\n'); this.mappingList = rows.filter(row => row.trim()).map(row => { const [keyStr, valueStr] = row.split(','); return { id: parseInt(keyStr.trim(), 10), code: valueStr.trim().replace(/^"|"$/g, '') } }).filter(item => !isNaN(item.id)); // 对象数组查询方法 getMappingValueFromList(input: number): string | undefined { return this.mappingList.find(item => item.id === input)?.code; }
使用示例
输入51调用getMappingValue(51)即可直接返回3847489。
内容的提问来源于stack exchange,提问作者Steven Glasius
相关产品推荐
相关产品推荐

