将驼峰和下划线数据互转

// 字符串的下划线格式转驼峰格式,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
}

 

posted @ 2019-01-27 18:08  星陨的菲  阅读(623)  评论(0编辑  收藏  举报