Skip to content

Instantly share code, notes, and snippets.

@begin-again
Created October 17, 2019 18:10
Show Gist options
  • Save begin-again/2ef3ba767b70175aff323cc51652f323 to your computer and use it in GitHub Desktop.
Save begin-again/2ef3ba767b70175aff323cc51652f323 to your computer and use it in GitHub Desktop.
Transposing keys
// The problem is that I need to change an objetc's key names
// the question then is which is better?
// method brute force
const toLocal = (item) => {
const newItem = {};
newItem.itemId = item.ITEM_ID;
newItem.itemTitle = item.ITEM_TITLE
newItem.checklistIntId = item.CHECKLIST_INSTANCE_ID
// ...
return newItem
}
// local objects will have keys that dont translate to server
// but we don't need an object with those unmatched keys
const toServer = (item) => {
const newItem = {}
newItem.itemId = item.ITEM_ID;
newItem.itemTitle = item.ITEM_TITLE
newItem.checklistInstanceId = item.CHECKLIST_INSTANCE_ID
// ...
return newItem
}
// method sexy
const keyMap = [
{server: 'INSTANCE_TITLE', local: 'checklistInstanceTitle'},
{server: 'ITEM_ID', local: 'itemId'},
{server: 'CHECKLIST_ITEM_ID', local: 'checklistItemId'},
{server: 'CHECKLIST_INSTANCE_ID', local: 'checklistInstanceId'},
{server: 'IS_ACTIVE', local: 'isActive'},
{server: 'ITEM_ORDER', local: 'itemOrder'},
{server: 'DEADLINE', local: 'deadline'},
{server: 'ITEM_TITLE', local: 'itemTitle'},
{server: 'OPEN_DATE', local: 'openDate'},
{server: 'SECTION_ID', local: 'sectionId'},
{server: 'SECTION_NAME', local: 'sectionName'},
{server: 'SECTION_ORDER', local: 'sectionOrder'},
]
const findKeyPair = (key) => {
return keyMap.find( pair => pair.server === key || pair.local === key)
}
const swapKeys = (item, action = 'server') => {
const newItem = {};
Object.keys(item).map( oKey => {
const pair = findKeyPair(oKey);
if(pair) {
if(action === 'server') {
newItem[pair.server] = item[pair.local]
}
else {
newItem[pair.local] = item[pair.server]
}
}
})
return newItem;
}
const toLocal = (item) => swapKeys(item, 'local')
const toServer = (item) => swapKeys(item, 'server')
@begin-again
Copy link
Author

Usage would be:

localItems = serverItems.map(key => toLocal(key))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment