驼峰命名与下划线相互转换

js将下划线命名与驼峰式命名相互转换

驼峰

下划线

下划线转驼峰式命名


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

// JSON对象的key值转换为驼峰式
function jsonToHump(obj) {
    if (obj instanceof Array) {
        obj.forEach(function (v, i) {
            jsonToHump(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]
            }
            jsonToHump(obj[newKey])
        })
    }
    return obj
}

驼峰式命名转换为下划线


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


// JSON对象的key值转换为下划线格式
function jsonToUnderline(obj) {
    if (obj instanceof Array) {
        obj.forEach(function (v, i) {
            jsonToUnderline(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]
            }
            jsonToUnderline(obj[newKey])
        })
    }
    return obj
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容