JS 对象按照value排序的实现

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
function objsortbyval(obj) {
var keyArr = [],valArr = [];
for (var key in obj) {
keyArr.push(key);
valArr.push(obj[key]);
}
for (var i = 0, len = valArr.length; i < len; i++) {
for (var j = 0; j < len - i; j++) {
var keyTemp, valTemp;
if (valArr[j] < valArr[j + 1]) {
valTemp = valArr[j];
valArr[j] = valArr[j + 1];
valArr[j+1] = valTemp;
keyTemp = keyArr[j];
keyArr[j] = keyArr[j + 1];
keyArr[j+1] = keyTemp;
}
}
}
var newobj={};
for(var i=0;i<valArr.length;i++){
newobj['"'+keyArr[i]+'"']=valArr[i];
}
console.log(newobj);
}

var obj = {
"apple": 124,
"banana": 23,
"melon": 19,
"pear": 100,
"orange": 68
};

objsortbyval(obj);

评论