o2o-mapper
一个可扩展的对象转换工具
使用
// ES6 引入
import { map, rules, custom } from 'o2o-mapper'
// 或
import mapper from 'o2o-mapper'
const { map, rules, custom } = mapper
// CommonJS 引入
const { map, rules, custom } = require('o2o-mapper')
// 开始使用
const target = map(source, rule1, rule2, ...)
示例
import { map, rules, custom } from 'o2o-mapper'
// 简单对象映射
map({
name: 'myName',
value: 'aValue'
}, {
newNameKey: 'name',
nonExistsKey: 'non-exists'
}) === {
newNameKey: 'myName',
nonExistsKey: undefined
}
// 嵌套对象映射
map({
outer: 'outerVal',
nested: {
inner: 'innerVal'
}
}, {
outer: 'outer',
inner: rules('nested', 'inner'),
newKey: rules('nested', {
innerKey: 'inner'
})
}) === {
outer: 'outerVal',
inner: 'innerVal',
newKey: {
innerKey: 'innerVal'
}
}
// 对象安全取值
map({
key1: null
}, rules(
'key1',
'key2',
'key3'
)) === undefined
// 自定义规则(去除空值键)
custom('object', 'null', (source, rule) => {
source = Object.assign({}, source)
for (const key in source) {
if (source.hasOwnProperty(key) && typeof source[key] === 'undefined') {
delete source[key]
}
}
return source
})
map({
key: 'test',
empty: undefined
}, null) === {
key: 'test'
}
实现原理
根据源对象的类型和规则对象的类型,调用对应的转换函数。由转换函数返回转换后的目标对象。
对象可识别为如下类型:
null
undefined
string
number
boolean
function
object
array
symbol
bigint
这基本上是typeof
的返回结果,但null
和array
已经从object
类型中区分出来。
API
map
/**
* 将源对象根据一系列规则转换成目标对象
* @param {any} source 源对象
* @param {any[]} rules 转换规则,可传入多个
* @returns {any} 目标对象
*/
map(source, ...rules)
rules
/**
* 将多个规则合并为单个规则
* @param {any[]} rules 转换规则列表
* @returns {Rule} 合并后的规则对象,可直接传入`map`中
*/
rules(...rules)
custom
/**
* 自定义转换函数
* @param {string} sourceType 源对象的格式,传入`all`表示任意格式
* @param {string} ruleType 规则对象的格式,传入`all`表示任意格式
* @param {(source, rule) => any} 规则函数,接受源对象和规则对象,返回目标对象
* @returns {void} 该函数无返回值
*/
custom(sourceType, ruleType, fn)
内置转换函数
any-function
任意类型的源对象和函数类型的规则对象。直接将源对象作为参数传入规则函数,规则函数的返回结果作为目标对象。
any-string
任意类型的源对象和字符串类型的规则对象。将规则字符串作为key
,尝试在源对象上取属性。若失败(源对象为null
或undefined
),则返回undefined
。
any-object
任意类型的源对象和对象类型的规则对象。将返回一个和规则对象结构相似的对象,规则对象的键映射为目标对象的键。规则对象的键值作为规则应用到源对象上,得到的结果作为目标对象对应的键值。