javascript對JSON數(shù)據(jù)排序的3個例子
一、適用于數(shù)字排序和字幕排序
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、數(shù)字排序
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:關(guān)于json操作,這里再為大家推薦幾款比較實(shí)用的json在線工具供大家參考使用:
在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat
在線json壓縮/轉(zhuǎn)義工具:
http://tools.jb51.net/code/json_yasuo_trans
C語言風(fēng)格/HTML/CSS/json代碼格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
相關(guān)文章
javascript 正則表達(dá)式觸發(fā)函數(shù)進(jìn)行高級替換
如果在正則表達(dá)式中定義了子匹配,那么參數(shù)的長度會隨著子匹配的個數(shù)改變,如果沒有定義子匹配,那么長度是固定的。2010-03-03
javascript中slice(),splice(),split(),substring(),substr()使用方法
這篇文章主要介紹了javascript中slice(),splice(),split(),substring(),substr()使用方法,需要的朋友可以參考下2015-03-03
extract-text-webpack-plugin用法詳解
這篇文章主要介紹了extract-text-webpack-plugin用法詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
javascript setTimeout()傳遞函數(shù)參數(shù)(包括傳遞對象參數(shù))
由于需要,我要用到setTimeout()并且在里邊的函數(shù)參數(shù)傳遞一個參數(shù),就像這樣setTimeout("fun(參數(shù))", 1000)。但是以我這種寫法,js會報錯,說‘參數(shù)’未定義。2010-04-04
JavaScript實(shí)現(xiàn)在數(shù)組中查找不同順序排列的字符串
這篇文章主要介紹了JavaScript實(shí)現(xiàn)在數(shù)組中查找不同順序排列的字符串,本文用兩個方法解決了這道算法題,需要的朋友可以參考下2014-09-09
JavaScript中的document.querySelector()方法使用詳解
HTML的DOM querySelector()方法可以不需要額外的jQuery等支持,也可以方便的獲取DOM元素,語法跟jQuery類似,這篇文章主要給大家介紹了關(guān)于JavaScript中document.querySelector()方法使用的相關(guān)資料,需要的朋友可以參考下2024-06-06
js實(shí)現(xiàn)文件上傳功能 后臺使用MultipartFile
這篇文章主要為大家詳細(xì)介紹了純js實(shí)現(xiàn)最簡單的文件上傳功能,后臺使用MultipartFile,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09

