简体   繁体   English

如何在pascal和camel case之间转换回来和JSON键?

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

I have a front end on JS and backend in other language.我有一个 JS 前端和其他语言的后端。 It's more covenient for me to with JSON in camel case on backend, whread on front end -- with camel case.对我来说,使用 JSON 在后端的骆驼箱中,在前端的 whread 中使用骆驼箱更方便。

I decide that I'll do conversion of the JSON key on front end rather on back end.我决定在前端而不是后端转换 JSON 键。 What are the easiest and performant ways of doing so in JS?在 JS 中这样做的最简单和高效的方法是什么?

Note that JSON has multiple levels of nesting.请注意,JSON 具有多级嵌套。

Lodash has some very handy functions to help with this kind of conversion. Lodash 有一些非常方便的函数来帮助进行这种转换。 _.camelCase will convert a string to camel case. _.camelCase会将字符串转换为驼峰式大小写。

It's then very easy to to the same with pascal case (using a combination of _.upperFirst and _.camelCase.然后很容易与帕斯卡大小写相同(使用_.upperFirst和 _.camelCase 的组合。

To convert an object from one case style to another we can create a conversion function changeCase then call recursively on an object:要将 object 从一种 case 样式转换为另一种,我们可以创建转换 function changeCase然后递归调用 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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