Skip to content

Instantly share code, notes, and snippets.

@MinweiShen
Created September 14, 2019 05:02
Show Gist options
  • Save MinweiShen/2ee26a5a827a84a6e970cf036c2930a1 to your computer and use it in GitHub Desktop.
Save MinweiShen/2ee26a5a827a84a6e970cf036c2930a1 to your computer and use it in GitHub Desktop.
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