Created
September 14, 2019 05:02
-
-
Save MinweiShen/2ee26a5a827a84a6e970cf036c2930a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const get = require('lodash/get'); | |
function transform(source, schema, ...ext) { | |
const result = Object.create(null); | |
for (let prop of Object.getOwnPropertyNames(schema)) { | |
if (typeof schema[prop] === 'function') { | |
result[prop] = schema[prop](source[prop], source); | |
} else { | |
result[prop] = schema[prop]; | |
} | |
} | |
return Object.assign({}, ...ext, result); | |
} | |
const source = { | |
name: 'name', | |
users: [ | |
{ | |
name: 'user1', | |
age: 28 | |
}, { | |
name: 'user2', | |
age: 12 | |
} | |
], | |
index: 1, | |
meta: { | |
error: null, | |
status: 'ok' | |
} | |
}; | |
const schema = { | |
status: (_, source) => get(source, 'meta.status'), | |
name: value => `${value} modified`, | |
users: function(value, source) { | |
return value.map(v => ({ | |
name: get(v, 'name'), | |
age: get(v, 'age'), | |
status: get(source, 'meta.status'), | |
})); | |
}, | |
}; | |
console.log(transform(source, schema, source)) | |
console.log(transform(source, schema, source, {ext: 'v1', ext2: ['v2']})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment