问题
I'm attempting to sort this JSON object:
JSONObject = {
"command": [{
"geobox": [...],
"jobName": "...",
"keywords": ["..."],
"users": ["..."]
}, {
"geobox": [...],
"jobName": "...",
"keywords": ["...", "..."],
"users": ["...", "...", "..."]
}],
"type": "..."
}
It has "command" which is an array of nested json objects and "type" which I don't really care about. I want it to sort the array of nested json objects in "command" in alphabetical order based on the jobName value. I tried something like this but it didn't work.
JSONObject.command.sort(function (a, b) {
return JSONObject.command[a].jobName - JSONObject.command[b].jobName
});
回答1:
var compareStr = function (a, b) {
if (a.jobName == b.jobName)
return 0;
if (a.jobName > b.jobName)
return 1;
return -1;
};
JSONObject.command.sort(compareStr);
来源:https://stackoverflow.com/questions/11565841/sorting-nested-json-array