js实现automapper
实现 JavaScript 对象映射(AutoMapper)
在 JavaScript 中,可以通过手动编写映射逻辑或使用第三方库来实现类似 AutoMapper 的功能。以下是几种常见的方法:
手动实现对象映射
通过编写自定义函数,手动将源对象的属性映射到目标对象。
function mapObject(source, mappingConfig) {
const target = {};
for (const key in mappingConfig) {
if (mappingConfig.hasOwnProperty(key)) {
const sourceKey = mappingConfig[key];
target[key] = source[sourceKey];
}
}
return target;
}
// 示例用法
const source = { firstName: 'John', lastName: 'Doe' };
const mappingConfig = { name: 'firstName', surname: 'lastName' };
const target = mapObject(source, mappingConfig);
console.log(target); // { name: 'John', surname: 'Doe' }
使用第三方库
一些流行的 JavaScript 库可以简化对象映射过程:
- object-mapper
提供灵活的映射规则,支持嵌套对象和数组映射。
const objectMapper = require('object-mapper');
const source = { firstName: 'John', lastName: 'Doe' };
const map = {
'firstName': 'name',
'lastName': 'surname'
};
const target = objectMapper(source, map);
console.log(target); // { name: 'John', surname: 'Doe' }
- map-factory
支持复杂映射逻辑,包括条件映射和转换函数。
const mapFactory = require('map-factory');
const source = { firstName: 'John', lastName: 'Doe' };
const mapper = mapFactory()
.map('firstName').to('name')
.map('lastName').to('surname');
const target = mapper.execute(source);
console.log(target); // { name: 'John', surname: 'Doe' }
- lodash.pick 或 lodash.transform
使用 Lodash 工具库进行简单属性提取或转换。
const _ = require('lodash');
const source = { firstName: 'John', lastName: 'Doe', age: 30 };
const target = _.pick(source, ['firstName', 'lastName']);
console.log(target); // { firstName: 'John', lastName: 'Doe' }
支持嵌套对象和复杂映射
如果需要处理嵌套对象或复杂逻辑,可以扩展手动映射函数或使用库的高级功能。
function deepMapObject(source, mappingConfig) {
const target = {};
for (const key in mappingConfig) {
if (mappingConfig.hasOwnProperty(key)) {
const sourceKey = mappingConfig[key];
if (typeof sourceKey === 'object') {
target[key] = deepMapObject(source[key], sourceKey);
} else {
target[key] = source[sourceKey];
}
}
}
return target;
}
// 示例用法
const source = {
user: { firstName: 'John', lastName: 'Doe' },
age: 30
};
const mappingConfig = {
name: 'user.firstName',
details: {
surname: 'user.lastName',
age: 'age'
}
};
const target = deepMapObject(source, mappingConfig);
console.log(target);
// { name: 'John', details: { surname: 'Doe', age: 30 } }
使用 ES6 特性简化映射
通过解构赋值和展开运算符,可以快速实现简单映射。

const source = { firstName: 'John', lastName: 'Doe' };
const { firstName: name, lastName: surname } = source;
const target = { name, surname };
console.log(target); // { name: 'John', surname: 'Doe' }
以上方法可以根据需求选择适合的方案,手动实现适合简单场景,而第三方库更适合复杂映射需求。






