如何基于DTO指令实现含数组属性的通用数据结构映射?
数组属性映射扩展实现方案
核心逻辑
要实现数组属性的映射,核心是识别映射规则中的数组路径,遍历源数组的每个元素,对单个元素复用已有的对象属性映射逻辑,最后将处理后的元素集合赋值到目标数组路径。
具体执行步骤:
- 拆分映射规则的目标路径与源路径,分离出数组节点路径和元素属性名
- 从源数据中提取目标数组,遍历每个元素提取对应属性
- 构建目标数组的元素结构,将完整数组赋值到结果的对应路径
代码实现(基于Lodash)
以下是在原有对象映射基础上扩展数组支持的示例代码:
const _ = require('lodash'); function mapData(source, dtoRules) { const result = {}; Object.entries(dtoRules).forEach(([targetPath, sourcePath]) => { // 拆分目标路径:数组节点路径 + 元素属性 const targetSegments = targetPath.split('.'); const targetArrayPath = targetSegments.slice(0, -1).join('.'); const targetProp = targetSegments.at(-1); // 拆分源路径:源数组路径 + 元素属性 const sourceSegments = sourcePath.split('.'); const sourceArrayPath = sourceSegments.slice(0, -1).join('.'); const sourceProp = sourceSegments.at(-1); const sourceArray = _.get(source, sourceArrayPath); if (Array.isArray(sourceArray)) { // 遍历源数组,逐个元素映射属性 const targetArray = sourceArray.map(item => ({ [targetProp]: _.get(item, sourceProp) })); // 将目标数组写入结果的对应路径 _.set(result, targetArrayPath, targetArray); } else { // 原有普通对象属性映射逻辑 const value = _.get(source, sourcePath); _.set(result, targetPath, value); } }); return result; } // 测试示例 const source = { products: [ { title: '无线耳机', price: 399 }, { title: '智能手表', price: 1299 } ] }; const dtoRules = { 'nodes.edges.title': 'products.title', 'basic.info': 'products[0].title' // 兼容原有普通属性映射 }; console.log(mapData(source, dtoRules)); // 输出: // { // nodes: { edges: [ { title: '无线耳机' }, { title: '智能手表' } ] }, // basic: { info: '无线耳机' } // }
进阶优化方向
- 多属性映射:支持单个数组元素映射多个属性,可将规则调整为
'nodes.edges': { title: 'products.title', price: 'products.price' },遍历属性键值对构建元素 - 嵌套数组处理:针对多层嵌套数组,添加递归逻辑遍历处理每一层数组元素
- 异常兼容:增加源数组不存在、元素为空等场景的判断,避免执行报错
内容的提问来源于stack exchange,提问作者bonifacio
相关产品推荐
相关产品推荐

