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));