如何使用JavaScript

时间:2017-06-29 09:29:40

标签: javascript

我有以下对象:

Object { WK23: 12.52573059875292, WK22: 122.2625975869411, WK21:
78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2:
78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 }

是否可以按键排序,从WK1到WK100? 如何在JavaScript中执行此操作?

提前致谢,

3 个答案:

答案 0 :(得分:0)

不,你不能。对象键未订购。如果要对Object中的条目进行排序,则必须将其转换为Array。

var obj = {"WK23": 12.52573059875292, "WK22": 122.2625975869411};
var result = Object.keys(obj).map(function(key) {
  return [key, obj[key]];
});

// the result Array can then be sorted...
// result = [["WK23": 12.52573059875292], ["WK22": 122.2625975869411]]

var sorted = result.sort(function(a,b){
    var num_a = parseInt(a[0].replace("WK", ""));
    var num_b = parseInt(b[0].replace("WK", ""));
    return num_a > num_b;
});
// sorted = [["WK22": 122.2625975869411], ["WK23": 12.52573059875292]]

答案 1 :(得分:0)

试试这个,你可以改变顺序并分配给不同的对象



var unordered={ WK23: 12.52573059875292, WK22: 122.2625975869411, WK21: 78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2: 78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 }

console.log(JSON.stringify(unordered));


const ordered = {};
Object.keys(unordered).sort(function(a,b){
var a=a.split("WK")[1];
var b=b.split("WK")[1];
return a-b
}).forEach(function(key) {
  ordered[key] = unordered[key];
});

console.log(JSON.stringify(ordered));




答案 2 :(得分:0)

你去吧

const sample = { WK23: 12.52573059875292, WK22: 122.2625975869411, WK21:
78.48714311048059, WK20: 87.14214810403018, WK26: 78.52625051674245, WK25: 77.64480983891451, WK24: 67.42158281711342, WK2:
78.420343898902, WK3: 77.91344340707354, WK4: 77.29048185059888 };

const sorted = Object.keys(sample).sort().map(key => sample[key]);