JavaScript: Sort JSON Object Array Based On A Key Attribute

json arrary 的排序, 解法:

範例:

var array = [{    
    "EmployeeName": "John",    
    "Experience": "12",    
    "Technology": "SharePoint"    
}, {    
    "EmployeeName": "Charles",    
    "Experience": "9",    
    "Technology": "ASP.NET"    
}, {    
    "EmployeeName": "Jo",    
    "Experience": "3",    
    "Technology": "JAVA"    
}, {    
    "EmployeeName": "Daine",    
    "Experience": "7",    
    "Technology": "Sql Server"    
}, {    
    "EmployeeName": "Zain",    
    "Experience": "6",    
    "Technology": "C#"    
}];    
//Comparer Function    
function GetSortOrder(prop) {    
    return function(a, b) {    
        if (a[prop] > b[prop]) {    
            return 1;    
        } else if (a[prop] < b[prop]) {    
            return -1;    
        }    
        return 0;    
    }    
}    
    
array.sort(GetSortOrder("EmployeeName")); 
document.write("Sorted Employee Names : ");    
for (var item in array) {    
    document.write("<br>" + array[item].EmployeeName);    
}    
    
array.sort(GetSortOrder("Technology")); 
document.write("<br><br> Sorted Technology Names : ");    
for (var item in array) {    
    document.write("<br>" + array[item].Technology);    
}  

Output Sorted Employee Names:

Charles
Daine
Jo
JohnZainSorted Technology

Sorted Technology:

ASP.NET
C#
JAVA
SharePoint

解法2:
https://dev.to/slimpython/sort-array-of-json-object-by-key-value-easily-with-javascript-3hke

suppose this is the array of JSON object

var data = [
  { id: 2, name: "FIAT", active: true, parentId: "1" },
  { id: 11, name: "BMW", active: true, parentId: "1" },
  { id: 3, name: "RENAULT", active: false, parentId: "1" },
  { id: 0, name: "AUDI", active: true, parentId: "1" },
];

now if you want to sort this array of json object by id basis you can simply do this by

data = data.sort((a, b) => {
  if (a.id < b.id) {
    return -1;
  }
});

result would be :

 [
  { id: 0, name: 'AUDI', active: true, parentId: '1' },
  { id: 2, name: 'FIAT', active: true, parentId: '1' },
  { id: 3, name: 'RENAULT', active: false, parentId: '1' },
  { id: 11, name: 'BMW', active: true, parentId: '1' }
] 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *