You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 13:52:05