使用格式化函数对字段进行进行格式化
query.to(field, type, options)
field
: {String} 需要格式化的字段type
: {String} 指定格式化方式(内置的格式化函数或者自定义的格式化函数名称)options
: {Object} 可用的配置项args
: {Array} 传递给格式化函数的除了value
之外的剩余参数, 如:[arg1, arg2, [arg3]...]
new
: {Boolean | String} 是否生成新的字段, 默认false
false
: 不生成新字段,直接使用格式化后的值重置原字段true
: 生成新字段,保留原字段。新字段被标识为$原字段名
,如title
=>$title
string
: 生成新字段,保留原字段。使用指定的名称来生成一个新字段,新字段会被自动添加$
前缀,如customTitle
=>$customTitle
handler
: {Function | null} 局部格式化函数,该格式化函数仅对当前使用有效,缺省值为null
var sourceData = [
{
title: 'title',
createAt: '2017-09-20T13:14:06.312Z',
views: '322'
}
]
var query = new Query(sourceData)
// 1. 使用内置格式化函数
// 1.1 生成新字段
query
.to('createAt', 'date', {args: ['yy-MM'], new: 'myDate'})
.find()
// [
// {
// title: 'title',
// createAt: '2017-09-20T13:14:06.312Z',
// views: '322',
// '$myDate': '2017-09'
// }
// ]
// 1.2 不生成新字段
query
.to('createAt', 'number', {new: false})
.find()
// [
// {
// title: 'title',
// createAt: '2017-09-20T13:14:06.312Z',
// views: 322 // 字符串被转换为数字
// }
// ]
// 2. 使用自定义格式化函数
// 2.1 注册全局格式化函数
Query.hooks('formatTitle', value => {
return '格式化后的' + value
})
query
.to('title', 'formatTitle', {new: true})
.find()
// [
// {
// title: 'test',
// createAt: '2017-09-20T13:14:06.312Z',
// views: '322',
// '$title': '格式化后的title'
// }
// ]
// 2.2 使用局部格式化函数
query
.to('title', null, {new: true, handler(value) {
return '使用局部格式化函数格式化的' + value
}})
.find()
// [
// {
// title: 'test',
// createAt: '2017-09-20T13:14:06.312Z',
// views: '322',
// '$title': '使用局部格式化函数格式化的title'
// }
// ]