Last active
September 19, 2018 13:14
-
-
Save drewsmith/1424c65a6e627f790b14e69d9378259f to your computer and use it in GitHub Desktop.
object conversion
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 importMemberObject = { | |
first_name: 'Jason', | |
last_name: 'Brady', | |
email_address: 'jason@email.com', | |
phone_number: '8167395555' | |
} | |
// will have to be hand crafted per congregation | |
const mappingConfig = { | |
Member: { | |
firstName: 'first_name', | |
lastName: 'last_name', | |
email: 'email_address' | |
}, | |
Phone: { | |
number: 'phone_number' | |
} | |
} | |
// without spread | |
/* | |
map = (mapperConfig, importMemberObject) => { | |
return Object.keys(mapperConfig).reduce((acc, val) => { | |
acc[val] = Object.keys(mapperConfig[val]).reduce((child_acc, child_val) => { | |
child_acc[child_val] = importMemberObject[mapperConfig[val][child_val]] | |
return child_acc | |
}, {}) | |
return acc | |
}, {}) | |
} | |
*/ | |
const forEachMap = (mappingConfig, importMemberObject) => { | |
const object = {} | |
const objectKeys = Object.keys(mappingConfig) | |
objectKeys.forEach(objectKey => { | |
object[objectKey] = {} | |
const propertyKeys = Object.keys(mappingConfig[objectKey]) | |
propertyKeys.forEach(propertyKey => { | |
object[objectKey][propertyKey] = importMemberObject[mappingConfig[objectKey][propertyKey]] | |
}) | |
}) | |
return object | |
} | |
// with spread | |
const map = (mapperConfig, importMemberObject) => { | |
return Object.keys(mapperConfig).reduce((acc, val) => ({ | |
...acc, | |
[val]: Object.keys(mapperConfig[val]).reduce((child_acc, child_val) => ({ | |
...child_acc, | |
[child_val]: importMemberObject[mapperConfig[val][child_val]] | |
}), {}) | |
}), {}) | |
} | |
const feJson = JSON.stringify(forEachMap(mappingConfig, importMemberObject)) | |
const mapJson = JSON.stringify(map(mappingConfig, importMemberObject)) | |
console.log(feJson) | |
console.log(mapJson) | |
console.log(mapJson === feJson) | |
/* | |
drew@drew-dell:~/code$ node reducer.js | |
{"Member":{"firstName":"Jason","lastName":"Brady","email":"jason@email.com"},"Phone":{"number":"8167395555"}} | |
{"Member":{"firstName":"Jason","lastName":"Brady","email":"jason@email.com"},"Phone":{"number":"8167395555"}} | |
true | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment