Sorting nested JSON array

三世轮回 提交于 2021-02-20 05:13:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!