One, suitable for numerical sorting and subtitle sorting
There are a number of ways to sort JSON, which is one of the simplest.
Copy Code code as follows:
var sortby = function (filed, rev, primer) {
Rev = (rev)? -1:1;
return function (A, b) {
A = a[filed];
b = b[filed];
if (typeof (primer)!= ' undefined ') {
A = Primer (a);
b = Primer (b);
}
if (a < b) {return Rev * 1;}
if (a > B) {return Rev * 1;}
return 1;
}
};
var obj = [
{b: ' 3 ', C: ' C '},
{b: ' 1 ', C: ' A '},
{b: ' 2 ', C: ' B '}
];
1, the number of sorting
Copy Code code as follows:
Obj.sort (SortBy (' B ', false, parseint));
Console.log (obj);
2. String sorting
Copy Code code as follows:
Obj.sort (SortBy (' B ', false, String));
Console.log (obj);
Two, JSON sort example 2
Copy Code code as follows:
var willsort = [
{
Name: ' Shangwenhe ',
AGE:25,
height:170
},
{
Name: ' Zhangsan ',
Age:31,
height:169
},
{
Name: ' Lisi ',
Age:31,
height:167
},
{
Name: ' Zhaowu ',
Age:22,
height:160
},
{
Name: ' Wangliu ',
Age:23,
height:159
}
];
/*
@function Jsonsort to sort JSON
JSON used to sort @param json
Key values sorted by @param key
*/
function Jsonsort (json,key) {
Console.log (JSON);
for (Var j=1,jl=json.length;j < jl;j++) {
var temp = Json[j],
val = Temp[key],
i = j-1;
while (i >=0 && json[i][key]>val) {
JSON[I+1] = Json[i];
i = i-1;
}
JSON[I+1] = temp;
}
Console.log (JSON);
return JSON;
}
var json = Jsonsort (willsort, ' age ');
Console.log (JSON);
Three, JSON sort example 3
Copy Code code as follows:
var people = [
{
Name: ' A75 ',
Item1:false,
Item2:false
},
{
Name: ' Z32 ',
Item1:true,
Item2:false
},
{
Name: ' E77 ',
Item1:false,
Item2:false
}];
function Sortbykey (array, key) {
Return Array.Sort (function (A, b) {
var x = A[key]; var y = B[key];
Return ((x < y)?-1: ((x > Y)? 1:0));
});
}
People = Sortbykey (People, ' name ');
PS: About JSON operation, here we recommend a few more practical JSON online tools for your reference to use:
Online JSON code inspection, inspection, landscaping, formatting tools:
Http://tools.jb51.net/code/json
JSON Online formatting tool:
Http://tools.jb51.net/code/jsonformat
Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson
JSON code online Format/beautify/compress/edit/Convert tools:
Http://tools.jb51.net/code/jsoncodeformat
Online JSON compression/escape tool:
Http://tools.jb51.net/code/json_yasuo_trans
C Language Style/html/css/json code formatting landscaping Tools:
Http://tools.jb51.net/code/ccode_html_css_json