如何在TypeScript中为嵌套对象实现指定字段映射?
问题描述
现有两个JavaScript对象:
let response = { offer: { custom_fields: { job_title: 'engineer' }, starts_at: 'test', job_post: 'test' } } let defaultFieldMapping = { "$.engagementData.title": { default: "Software Engineer", path: "$.offer.custom_fields.job_title", fieldName: 'Title' }, "$.engagementData.startDateUTC": { default: null, path: "$.offer.starts_at", }, }
需要生成如下结构的数组:
let expectedResult = [ { externalFieldId: '$.offer.custom_fields.job_title', integrationFieldId: '$.engagementData.title' }, { externalFieldId: '$.offer.starts_at', integrationFieldId: '$.engagementData.startDateUTC' }, { externalFieldId: '$.offer.job_post', integrationFieldId: '' }, ]
规则:若response.offer中的字段对应的JSON路径未出现在defaultFieldMapping的path属性中,则该条目的integrationFieldId设为空字符串。
解决方案
通过以下步骤实现需求:
- 提取
response中所有字段的完整JSON路径 - 构建反向映射表,快速匹配路径对应的集成字段ID
- 遍历路径生成符合要求的结果数组
代码实现
// 递归提取所有字段的完整JSON路径 function extractPaths(obj, parentPath = '$.offer') { let paths = []; for (const key in obj) { if (typeof obj[key] === 'object' && obj[key] !== null) { paths = paths.concat(extractPaths(obj[key], `${parentPath}.${key}`)); } else { paths.push(`${parentPath}.${key}`); } } return paths; } // 构建反向映射表:path -> integrationFieldId const pathToIntegrationMap = {}; for (const integrationId in defaultFieldMapping) { const path = defaultFieldMapping[integrationId].path; pathToIntegrationMap[path] = integrationId; } // 生成结果数组 const externalPaths = extractPaths(response.offer); const expectedResult = externalPaths.map(path => ({ externalFieldId: path, integrationFieldId: pathToIntegrationMap[path] || '' })); console.log(expectedResult);
代码说明
- extractPaths函数:递归遍历
response.offer的所有层级,拼接出每个字段的完整JSON路径,比如嵌套的job_title会生成$.offer.custom_fields.job_title。 - 反向映射表:将
defaultFieldMapping的映射关系反转,把path作为键、对应的集成字段ID作为值,避免遍历查找的低效。 - 结果生成:遍历所有提取的外部路径,通过映射表匹配对应的集成字段ID,无匹配项则用空字符串填充,最终组装成预期结构。
内容的提问来源于stack exchange,提问作者mani kandan
相关产品推荐
相关产品推荐

