将驼峰和下划线数据互转

Posted unreal-feather

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将驼峰和下划线数据互转相关的知识,希望对你有一定的参考价值。

// 字符串的下划线格式转驼峰格式,eg:hello_world => helloWorld
function underline2Hump(word) {
    return word.replace(/_(w)/g, function (all, letter) {
        return letter.toUpperCase()
    })
}

// 字符串的驼峰格式转下划线格式,eg:helloWorld => hello_world
function hump2Underline(word) {
    return word.replace(/([A-Z])/g, ‘_$1‘).toLowerCase()
}

// JSON对象的key值转换为驼峰式
function toHump(obj) {
    if (obj instanceof Array) {
        obj.forEach(function (v, i) {
            toHump(v)
        })
    } else if (obj instanceof Object) {
        Object.keys(obj).forEach(function (key) {
            var newKey = underline2Hump(key)
            if (newKey !== key) {
                obj[newKey] = obj[key]
                delete obj[key]
            }
            toHump(obj[newKey])
        })
    }
    return obj;
}

// 对象的key值转换为下划线格式
function toUnderline(obj) {
    if (obj instanceof Array) {
        obj.forEach(function (v, i) {
            toUnderline(v)
        })
    } else if (obj instanceof Object) {
        Object.keys(obj).forEach(function (key) {
            var newKey = hump2Underline(key)
            if (newKey !== key) {
                obj[newKey] = obj[key]
                delete obj[key]
            }
            toUnderline(obj[newKey])
        })
    }
    return obj;
}

export {
    toUnderline,
    toHump
}

 

以上是关于将驼峰和下划线数据互转的主要内容,如果未能解决你的问题,请参考以下文章

PHP把下划线分隔命名的字符串与驼峰式命名互转

java下划线与驼峰命名互转

Java-驼峰命名与下划线命名互转

jackson 常用注解,比如忽略某些属性,驼峰和下划线互转

Java/Spring/Jackson 驼峰-下划线字段转换

使用 Spark 编写数据集时,如何将驼峰式列名修改为带下划线的小写?