Skip to content

Instantly share code, notes, and snippets.

@Phoenix35
Last active September 13, 2019 13:14
Show Gist options
  • Save Phoenix35/e4bbe007914ecd353b6aaac381981e32 to your computer and use it in GitHub Desktop.
Save Phoenix35/e4bbe007914ecd353b6aaac381981e32 to your computer and use it in GitHub Desktop.
Quick thingy I made to copy while renaming certain props from an object to another
// PLEASE NOTE: this is LAZY! It will only yield properties that are part of `namesMap`
// not all properties of `source`
export function *transformPropertyNames (source, namesMap) {
for (
const [ entryKey, targetKey ] of typeof namesMap[Symbol.iterator] === "function"
? namesMap // iterable
: Object.entries(namesMap) // object-style
)
yield [ targetKey, source[entryKey] ];
}
export const xToXModel = (idFn => function xToXModel (propMap, propMapper = idFn) {
if (propMapper === idFn)
return x => Object.fromEntries(transformPropertyNames(x, propMap));
return function (x) {
const target = {};
for (const [ k, v ] of transformPropertyNames(x, propMap))
target[k] = propMapper(v, k);
return target;
};
})(x => x);
// Use
const userToUserModel = xToXModel({
CUSTOMERNUMBER: "CustomerNumber",
CITY: "City",
});
dbUsers.map(userToUserModel);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment