Last active
September 13, 2019 13:14
-
-
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
This file contains hidden or 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
| // 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