如何在TypeScript Node.js API中将分隔字符串转为指定键的JSON对象
解决方案:将竖线分隔字符串映射为指定JSON对象
步骤说明
- 先定义静态键集合,顺序必须和字符串中字段的顺序完全对应
- 用
split('|')把原始字符串拆分为值数组 - 遍历值数组,和静态键一一配对,同时将
Id字段转换为数字类型
完整TypeScript代码示例
// 定义静态键集合,顺序要和字符串中字段顺序匹配 const keys = ['Id', 'Name', 'City', 'Title', 'Status']; const string = "1234|Tom|NYC|Student|Active"; // 分割字符串为值数组 const values = string.split('|'); // 用reduce映射为目标对象 const result = values.reduce((acc, value, index) => { // 处理Id的类型转换 const key = keys[index]; acc[key] = key === 'Id' ? Number(value) : value; return acc; }, {} as Record<string, string | number>); console.log(result); // 输出:{ Id: 1234, Name: 'Tom', City: 'NYC', Title: 'Student', Status: 'Active' }
补充说明
- 如果担心字符串分割后的元素数量和键数组长度不匹配,可以加边界判断避免undefined键:
const result = values.reduce((acc, value, index) => { if (index < keys.length) { const key = keys[index]; acc[key] = key === 'Id' ? Number(value) : value; } return acc; }, {} as Record<string, string | number>);
- 你之前用
reduce未得到预期结果,大概率是没处理Id的类型转换、键数组顺序和值顺序不匹配,或是初始值的类型定义有问题。
内容的提问来源于stack exchange,提问作者Dinesh
相关产品推荐
相关产品推荐

