Last active
July 31, 2019 02:43
-
-
Save horiuchie/03081804c282a58048d99bf0ec91917f to your computer and use it in GitHub Desktop.
Rename keys with logic of renaming function.
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
import * as R from 'ramda'; | |
/* オブジェクトのプロタティ名をすべてtransformerに従って変換して返す */ | |
const renameKeysWith = R.curry((transformer, value) => { | |
if (R.is(Array)(value)) { | |
return R.map(renameKeysWith(transformer), value); | |
} | |
else if (R.is(Object)(value)) { | |
// [['PropA', valueA], ['PropB', valueB], ...] | |
const renamedPairs = R.map( | |
R.evolve({ 0: transformer, 1: renameKeysWith(transformer) }), | |
R.toPairs(value) | |
); | |
// { 'PropA': valueA, 'PropB': valueB, ... } | |
return R.fromPairs(renamedPairs); | |
} | |
else { | |
return value; | |
} | |
}); | |
/* PascalCaseからCamelCaseに変換する関数 */ | |
const camelizeFromPascal = R.o(R.join(''), R.adjust(0, R.toLower)); | |
/* オブジェクトのプロパティ名をPascalCaseからCamelCaseに変換する */ | |
const sampleData = { | |
ContentId: 123, | |
CommentList: [ { Message: 'Hi' }, { Message: 'Yo' } ], | |
PageSize: { Width: 100, Height: 200 } | |
}; | |
renameKeysWith(camelizeFromPascal, sampleData); | |
// {"commentList": [{"message": "Hi"}, {"message": "Yo"}], "contentId": 123, "pageSize": {"height": 200, "width": 100}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment