Skip to content

Instantly share code, notes, and snippets.

@horiuchie
Last active July 31, 2019 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save horiuchie/03081804c282a58048d99bf0ec91917f to your computer and use it in GitHub Desktop.
Save horiuchie/03081804c282a58048d99bf0ec91917f to your computer and use it in GitHub Desktop.
Rename keys with logic of renaming function.
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