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

如何使用TypeScript对Web API返回的JSON数据进行投影转换?

如何将Web API返回的验证错误JSON转换为TypeScript字符串数组?

我从Web API获取到如下JSON响应数据:

{ 
  "ClaimType": ["The length of 'Claim Type' must be at least 4 characters. You entered 2 characters."], 
  "ClaimValue": ["The length of 'Claim Value' must be at least 4 characters. You entered 1 characters."], 
  "Description": ["The length of 'Description' must be at least 10 characters. You entered 6 characters."] 
}

希望通过TypeScript将其投影转换为字符串数组,预期结果为类似 ["The length of 'Claim Type'...", "..."] 的形式,请问该如何实现?

没问题,这是个很常见的格式转换场景,我给你几种简单实用的TypeScript实现方式,你可以根据自己的需求选择:

方法1:一行代码搞定——Object.values() + flat()

这是最简洁的实现方式,利用ES6+的数组方法直接完成转换:

const apiResponse = { 
  "ClaimType": ["The length of 'Claim Type' must be at least 4 characters. You entered 2 characters."], 
  "ClaimValue": ["The length of 'Claim Value' must be at least 4 characters. You entered 1 characters."], 
  "Description": ["The length of 'Description' must be at least 10 characters. You entered 6 characters."] 
};

const errorMessages = Object.values(apiResponse).flat();
console.log(errorMessages);
// 输出:["The length of 'Claim Type'...", "The length of 'Claim Value'...", "The length of 'Description'..."]

简单解释:

  • Object.values(apiResponse)会提取对象中所有属性的取值,得到一个二维数组:[["ClaimType错误信息"], ["ClaimValue错误信息"], ["Description错误信息"]]
  • flat()方法会自动把嵌套的数组“扁平化”,直接把里面的字符串提取到外层数组,完美匹配你的预期结果。

方法2:手动遍历(兼容旧环境)

如果你的项目需要兼容不支持flat()的旧运行环境(比如部分老版本浏览器),可以用手动遍历的方式:

const apiResponse = { /* 你的API响应数据 */ };
const errorMessages: string[] = [];

// 遍历对象的每个属性
for (const field in apiResponse) {
  // 确保只处理对象自身的属性(避免遍历原型链上的无关属性)
  if (apiResponse.hasOwnProperty(field)) {
    // 把当前字段的错误数组展开,添加到结果数组中
    errorMessages.push(...apiResponse[field]);
  }
}

console.log(errorMessages);

方法3:函数式风格——Object.entries() + reduce()

如果你偏爱函数式编程的写法,用reduce也能实现:

const apiResponse = { /* 你的API响应数据 */ };
const errorMessages = Object.entries(apiResponse).reduce((acc, [_, messages]) => {
  // 把当前字段的错误数组和累加器合并
  return [...acc, ...messages];
}, [] as string[]);

console.log(errorMessages);

解释:

  • Object.entries()会返回对象的键值对数组,比如[["ClaimType", ["错误信息"]], ["ClaimValue", ["错误信息"]], ...]
  • reduce方法遍历这些键值对,每次把当前字段的错误数组展开后合并到累加器acc里,最终得到完整的错误字符串数组。

内容的提问来源于stack exchange,提问作者Shaik Hafeef

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:48:28