js深拷贝对象并根据key字母排序-摘要

let data = {
    "params": {
      "id": 514,
        "storeCode": "5139",
        "channelKey": "XINXIANG",
        "channelOrderSn": "2513920051119292641272",
        "status": "CHECKING",
        "return_type": "FULL",
        "createdAt": "2020-05-13 13:58:47",
        "goodsList": [
            {
                "spuCode": "660317",
                "goodsName": "招牌拌面葱油味1袋",
                "quantity": 1
            },
            {
                "spuCode": "660313",
                "goodsName": "招牌劲道风味拌面1盒",
                "quantity": 1
            },
            {
                "spuCode": "660321",
                "goodsName": "招牌拌面椒麻味1袋",
                "quantity": 1
            }
        ]
    },
    "serverKey": "oms",
    "format": "json",
    "sign": "{{sign}}",
    "timestamp": "{{timestamp}}",
    "version": "1.0"
}
// 检测数据类型
function checkedType(data) {
    return Object.prototype.toString.call(data).slice(8, -1)
}
// 将对象排序
function sortObj(obj) {
    if (checkedType(obj) === 'Object') {
        var keys = Object.keys(obj).sort();
        var arr = {};
        for (var i in keys) {
            var a = obj[keys[i]];
            arr[keys[i]] = obj[keys[i]];
        }
        return arr;
    } else {
        return obj;
    }
}

function cloneAndSort(data) {
    let result;
    let dataType = checkedType(data);
    if (dataType === 'Object') { // 对象
        result = {}
    } else if (dataType === 'Array') { // 数组
        result = []
    } else {
        return data;
    }
    
    for (let i in data) {
        if (checkedType(data[i]) === 'Object' || checkedType(data[i]) === 'Array') { //对象/数组里嵌套了对象/数组,递归
            result[i] = cloneAndSort(data[i]);
        } else { 
            result[i] = data[i];
        }
    }
    return sortObj(result);
}

console.log('排序key之后的结果', cloneAndSort(data));
全部为原创文章,转载请注明。
个人站点helijun.com.cn,欢迎指导交流....

posted @ 2020-05-15 10:08  微人类  阅读(175)  评论(0编辑  收藏  举报