多供应商产品JSON格式映射:深层属性映射实现方案咨询
问题:多供应商产品数据的深层属性映射实现
我需要对接多个供应商的产品数据,每个供应商的数据模型都不一样。现在要创建映射规则来提取并转换为统一的Product类型,但在处理深层属性映射时遇到了问题:比如我的Product类型里只有单个price字段,而供应商数据里对应的是嵌套的prices.USD属性。希望找到一种简便的解析方式,同时映射规则要能存到数据库(比如用JSON格式存储)。
类型定义
目标Product类型
type Product = { name: string; description: string; price: number; }
供应商1的产品类型
type Supplier1Product = { id: string; product_name: string; product_description: string; prices: { EUR: number; USD: number; } }
当前映射尝试
我原本想直接用字符串路径作为映射值:
const mapping = { name: 'product_name', description: 'product_description', price: 'prices.USD', }
希望能像这样直接取值:
const productPrice = supplierProduct[mapping.price];
但显然这种方式无法获取深层嵌套的属性值。
理想方案要求
- 映射规则可存储为JSON格式,能存入数据库
- 可以简便地根据映射规则从供应商数据中提取深层属性值
解决方案
1. 实现路径解析工具函数
写一个通用函数,拆分路径字符串并递归遍历对象,获取深层属性值:
function getNestedValue(obj: any, path: string, defaultValue?: any): any { return path.split('.').reduce((current, key) => { if (current === undefined) return defaultValue; // 兼容数组索引路径(如`items.0.name`) const index = parseInt(key, 10); return isNaN(index) ? current[key] : current[index]; }, obj) ?? defaultValue; }
2. 基于映射规则转换数据
用解析函数配合映射规则,批量转换供应商数据到目标类型:
function transformProduct(supplierData: Supplier1Product, mapping: Record<string, string>): Product { return { name: getNestedValue(supplierData, mapping.name, ''), description: getNestedValue(supplierData, mapping.description, ''), price: getNestedValue(supplierData, mapping.price, 0), }; } // 示例使用 const supplierProduct: Supplier1Product = { id: '123', product_name: 'Test Product', product_description: 'A test product', prices: { EUR: 29.99, USD: 34.99 } }; const product = transformProduct(supplierProduct, mapping); // 输出:{ name: 'Test Product', description: 'A test product', price: 34.99 }
3. 映射规则的存储
映射规则是纯字符串键值对,直接转JSON即可存入数据库:
{ "name": "product_name", "description": "product_description", "price": "prices.USD" }
读取时解析为对象就能直接使用。
内容的提问来源于stack exchange,提问作者LazioTibijczyk
相关产品推荐
相关产品推荐

