纯记录,原出处:
https://gist.github.com/elad-yosifon/300b89ec5479b9b712b7
红线处有点问题,没法处理null值:
所以,我改了一点,加上对null值的判断:
完整代码如下:
function sortJSON(object) {if (object instanceof Array) {for (var i = 0; i < object.length; i++) {object[i] = sortJSON(object[i]);}return object;} else if (typeof object != "object" || object == null) return object;var keys = Object.keys(object);keys = keys.sort();var newObject = {};for (var i = 0; i < keys.length; i++) {newObject[keys[i]] = sortJSON(object[keys[i]])}return newObject;}