我是靠谱客的博主 认真仙人掌,这篇文章主要介绍Javascript实现对Json数组排序,现在分享给大家,希望可以做个参考。

一、适用于数字排序和字符排序(最简单的一种):
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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'} ]; //数字排序 obj.sort(sortBy('b', false, parseInt)); console.log(obj); //字符排序 obj.sort(sortBy('b', false, String)); console.log(obj);
二、JSON排序例子2
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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 对json排序 @param json 用来排序的json @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);
三、JSON排序例子3
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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');

转自:http://www.jb51.net/article/48941.htm

最后

以上就是认真仙人掌最近收集整理的关于Javascript实现对Json数组排序的全部内容,更多相关Javascript实现对Json数组排序内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(79)

评论列表共有 0 条评论

立即
投稿
返回
顶部