將駝峯和下劃線數據互轉

// 字符串的下劃線格式轉駝峯格式,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
}
相關文章
相關標籤/搜索