js/ts 前端转驼峰命名(Newtonsoft.Json版)
Newtonsoft.Json转驼峰源码:
https://github.com/JamesNK/Newtonsoft.Json/issues/2187#issuecomment-538740046
前端
/**
* 该源码来自Newtonsoft.Json原作者
* https://github.com/JamesNK/Newtonsoft.Json/issues/2187#issuecomment-538740046
*/
/**
* 字符串转驼峰命名
* 此方法与Newtonsoft.Json转驼峰方式对应(其源码如下)
* 参考:https://github.com/JamesNK/Newtonsoft.Json/blob/52190a3a3de6ef9a556583cbcb2381073e7197bc/Src/Newtonsoft.Json/Utilities/StringUtils.cs#L155
* @param value 待转换的字符串
*/
export function toCamelCase(value: string): string {
// nullish or empty or starting camel...
if (value === null || value === undefined || value.length === 0 || !isUpperCase(value[0])) { return value }
// convert
const chars = Object.assign([] as string[], value)
for (let i = 0; i < chars.length; i++) {
// if the 2nd char is not upper, we finished conversion...
if (i === 1 && !isUpperCase(chars[i])) { break }
const hasNext = (i + 1 < chars.length)
if (i > 0 && hasNext && !isUpperCase(chars[i + 1])) {
// if the next character is a space, which is not considered uppercase
// (otherwise we wouldn't be here...)
// we want to ensure that the following:
// 'FOO bar' is rewritten as 'foo bar', and not as 'foO bar'
// The code was written in such a way that the first word in uppercase ends when if finds an uppercase letter followed by a lowercase letter.
// Now a ' ' (space, (char)32) is considered not upper but in that case we still want our current character to become lowercase.
if (isSeparator(chars[i + 1])) {
chars[i] = chars[i].toLowerCase()
}
break
}
chars[i] = chars[i].toLowerCase()
}
return chars.join('')
}
function isUpperCase(value: string): boolean {
return value === value.toUpperCase()
}
function isSeparator(value: string): boolean {
// line separator/paragraph separator/space separators - https://www.compart.com/en/unicode/category
const separator = '\u2028\u2029\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'; return separator.indexOf(value) >= 0
}
export function camelizeDictionaryKeys(dictionary: Object): Object {
const result = {}
for (const key in dictionary) {
const camelKey = key
.split('.')
.map(part => toCamelCase(part))
.join('.')
result[camelKey] = dictionary[key]
}
return result
}
源码引用自:
https://github.com/JamesNK/Newtonsoft.Json/issues/2187#issuecomment-538740046