如何使用TypeScript从JSON文件的嵌套对象中根据值获取对应key
TypeScript 实现嵌套JSON产品key查找方案
前置配置
如果你的JSON是本地存储的文件,先在tsconfig.json中开启以下配置,支持TS直接导入JSON文件:
{ "compilerOptions": { "resolveJsonModule": true, "esModuleInterop": true } }
之后把你的示例JSON保存为productConfig.json放在项目目录下即可。
完整可运行代码
// 导入本地JSON文件,如果是接口请求拿到的JSON可以跳过这步,直接用请求返回的对象 import productConfig from './productConfig.json'; // 定义TS类型约束JSON结构,避免类型报错 type ProductSegment = { name: string; products: Record<string, string>; }; type ConfigType = Record<string, ProductSegment>; // 查找逻辑函数:传入配置对象和要匹配的目标值,返回对应key,找不到返回null function getProductKeyByValue(config: ConfigType, targetValue: string): string | null { // 遍历所有外层分段 for (const segment of Object.values(config)) { // 遍历当前分段下products的所有键值对 for (const [key, value] of Object.entries(segment.products)) { if (value === targetValue) { return key; } } } return null; } // 调用测试 const targetKey = getProductKeyByValue(productConfig as ConfigType, 'Test Actions'); if (targetKey) { console.log('匹配到的key:', targetKey); // 控制台输出 action,targetKey就是你需要的字符串变量 } else { console.log('未找到匹配的项'); }
补充说明
- 上述逻辑默认返回第一个匹配到的key,如果你存在多个products值重复、需要返回所有匹配key的需求,把返回值改为数组类型,把所有匹配到的key push进数组后统一返回即可。
- 如果你的JSON结构后续扩展了多层嵌套,只需要在遍历逻辑里对应增加层级遍历的代码即可。
内容的提问来源于stack exchange,提问作者vik_nag
相关产品推荐
相关产品推荐

