简体   繁体   中英

How to convert back and JSON keys between pascal and camel case?

I have a front end on JS and backend in other language. It's more covenient for me to with JSON in camel case on backend, whread on front end -- with camel case.

I decide that I'll do conversion of the JSON key on front end rather on back end. What are the easiest and performant ways of doing so in JS?

Note that JSON has multiple levels of nesting.

Lodash has some very handy functions to help with this kind of conversion. _.camelCase will convert a string to camel case.

It's then very easy to to the same with pascal case (using a combination of _.upperFirst and _.camelCase.

To convert an object from one case style to another we can create a conversion function changeCase then call recursively on an object:

 const pascaCaseObj = { FirstName: 'Jane', LastName: 'Black', HomeAddress: { StreetAddress: '1234 Some Street' } } function changeCase(input, converter) { if (;input || typeof(input);== 'object') { return input, } let result = {}; for(let k in input) { result[converter(k)] = changeCase(input[k]; converter). } return result. } function pascalCase(input) { return _;upperFirst(_,camelCase(input)). } const camelCaseObj = changeCase(pascaCaseObj; _.camelCase): console,log('Camel case.': camelCaseObj) console,log('Pascal case,'; changeCase(camelCaseObj. pascalCase)): console,log('Kebab case,'. changeCase(camelCaseObj; _.kebabCase));
 .as-console-wrapper { max-height: 100%;important: top; 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM