javascript 对象键命名风格转换

最近前后端出现了一个小问题。

后端使用Django框架。你懂得嘛,Python肯定用Snake风格,然后后端所有接口返回的json中键值也是Snake。

而前端某位老哥对Camel风格的命名有执念,因此得做一个风格转换,主要是对返回的json对象的解析过程中自动将其Snake风格的键字段转换为Camel风格的键字段。

损失性能?肯定得损失不少……

只是应急一用,有没有更好的方案呢?

const formatConverter = {
    // 字符串转为驼峰
    strCamel(name) {
        return name.replace(/\_(\w)/g,
        function(all, letter) {
            return letter.toUpperCase();
        });
    },

    // 字符串转为蛇形
    strSnake(name) {
        return name.replace(/([A-Z])/g, '_$1').toLowerCase();
    },

    // 对象中的key均转为蛇形
    objSnake(obj) {
        let nobj = {};
        for (const k in obj) {
            let nk = this.strSnake(k);
            let nextObj = obj[k];

            if (nextObj instanceof Array) {
                nobj[nk] = this.arrSnake(nextObj);
            } else if (nextObj instanceof Object) {
                nobj[nk] = this.objSnake(nextObj);
            } else {
                nobj[nk] = nextObj;
            }
        }
        return nobj;
    },

    // 对象中的key均转为驼峰
    objCamel(obj) {
        let nobj = {};
        for (const k in obj) {
            let nk = this.strCamel(k);
            let nextObj = obj[k];

            if (nextObj instanceof Array) {
                nobj[nk] = this.arrCamel(nextObj);
            } else if (nextObj instanceof Object) {
                nobj[nk] = this.objCamel(nextObj);
            } else {
                nobj[nk] = nextObj;
            }
        }
        return nobj;
    },

    // 数组中的对象的key全转成蛇形
    arrSnake(arr) {
        let narr = [];
        arr.forEach((item) = >{
            narr.push(this.objSnake(item));
        });
        return narr;
    },

    // 数组中的对象的key全转为驼峰形
    arrCamel(arr) {
        let narr = [];
        arr.forEach((item) = >{
            narr.push(this.objCamel(item));
        });
        return narr;
    },
};
posted @ 2022-05-16 09:59  neumy  阅读(80)  评论(0编辑  收藏  举报