javascript对JSON数据排序的3个例子
一、适用于数字排序和字幕排序
json 的排序方法有很多种,这是其中最简单的一种方法。
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、数字排序
console.log(obj);
2、字符串排序
console.log(obj);
二、JSON排序例子2
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
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:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans
C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
相关文章
javascript中slice(),splice(),split(),substring(),substr()使用方法
这篇文章主要介绍了javascript中slice(),splice(),split(),substring(),substr()使用方法,需要的朋友可以参考下2015-03-03
extract-text-webpack-plugin用法详解
这篇文章主要介绍了extract-text-webpack-plugin用法详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-02-02
javascript setTimeout()传递函数参数(包括传递对象参数)
由于需要,我要用到setTimeout()并且在里边的函数参数传递一个参数,就像这样setTimeout("fun(参数)", 1000)。但是以我这种写法,js会报错,说‘参数’未定义。2010-04-04
JavaScript中的document.querySelector()方法使用详解
HTML的DOM querySelector()方法可以不需要额外的jQuery等支持,也可以方便的获取DOM元素,语法跟jQuery类似,这篇文章主要给大家介绍了关于JavaScript中document.querySelector()方法使用的相关资料,需要的朋友可以参考下2024-06-06


最新评论