update mapper example

This commit is contained in:
dntzhang 2018-11-26 09:54:47 +08:00
parent 6ae01fbc6e
commit 7fef1d0bfc
1 changed files with 57 additions and 45 deletions

View File

@ -1,14 +1,11 @@
<script>
/**
* Auto map object's props to object's props.
* @method mapper
* @param {Object} From Object
* @param {Object} To Object(可选)
* @param {Object} Mapping Rules
* @return {Object} To Object
*/
* Auto map object's props to object's props.
* @method mapper
* @param {Object} options {from: .., to: .., rule: .. }
* @return {Object} To Object
*/
const mapper = function (options) {
const from = options.from
const to = options.to
const rules = options.rule
@ -19,31 +16,32 @@
res[key] = from[key]
})
rules && Object.keys(rules).forEach(key => {
const rule = rules[key]
const isPath = key.match(/\.|\[/)
if (typeof rule === 'function') {
if (isPath) {
setPathValue(res, key, rule.call(from))
rules &&
Object.keys(rules).forEach(key => {
const rule = rules[key]
const isPath = key.match(/\.|\[/)
if (typeof rule === 'function') {
if (isPath) {
setPathValue(res, key, rule.call(from))
} else {
res[key] = rule.call(from)
}
} else {
res[key] = rule.call(from)
if (isPath) {
setPathValue(res, key, rule)
} else {
res[key] = rule
}
}
} else {
if (isPath) {
setPathValue(res, key, rule)
} else {
res[key] = rule
}
}
})
})
return res
}
function setPathValue(obj, path, value) {
const arr = path.replace(/]/g, '').replace(/\[/g, '.').split('.')
const arr = path
.replace(/]/g, '')
.replace(/\[/g, '.')
.split('.')
let current = obj
for (let i = 0, len = arr.length; i < len; i++) {
@ -65,48 +63,62 @@
current = temp
}
}
//mapper 独立发布
var testObj = {
same: 10,
bleh: 4,
firstName: 'dnt',
lastName: 'zhang',
a: {
c: 10
}
}
var res = mapper({
from: {
same: 10,
bleh: 4,
firstName: 'dnt',
lastName: 'zhang',
a: {
c: 10
}
},
from: testObj,
to: { aa: 1 },
rule: {
dumb: 12,
func: function () {
return 8
},
b: function () {
return mapper({ from: this.a })
},
bar: function () {
return this.bleh
},
fullName: function () {
return this.firstName + this.lastName
},
'a[2].b[0]': function () {
'd[2].b[0]': function () {
return this.a.c
}
}
}
)
console.log(res.b === testObj.a) //false
console.log(JSON.stringify(res, null, 2))
// <!-- output
// {
// {
// "aa": 1,
// "same": 10,
// "bleh": 4,
// "firstName": "dnt",
// "lastName": "zhang",
// "a": {
// "c": 10
// },
// "dumb": 12,
// "func": 8,
// "b": {
// "c": 10
// },
// "bar": 4,
// "fullName": "dntzhang",
// "a": [
// "d": [
// null,
// null,
// {
@ -115,5 +127,5 @@
// ]
// }
// ]
// } -->
</script>
// }
</script>