我有下面的字典词典,我必须使用这种格式,因为我没有权力超过服务器端
{"1":{"aov":0,"oo":1,"ot":"Cem-Merve","pi":87},"2":{"aov":100,"oo":2,"ot":"Murat-Pelin","pi":88},"3":{"aov":0,"oo":3,"ot":"Fevzi-Azbiye","pi":85},"4":{"aov":0,"oo":4,"ot":"Burak-Gizem","pi":86},"21":{"aov":100,"oo":21,"ot":"Murat","pi":84,"ro":2},"22":{"aov":0,"oo":22,"ot":"Pelin","pi":83,"ro":2}}
我需要按字母顺序用Javascript按键排序,就像
一样{"1":{"aov":0,"oo":1,"ot":"Cem-Merve","pi":87},"2":{"aov":100,"oo":2,"ot":"Murat-Pelin","pi":88},"21":{"aov":100,"oo":21,"ot":"Murat","pi":84,"ro":2},"22":{"aov":0,"oo":22,"ot":"Pelin","pi":83,"ro":2},"3":{"aov":0,"oo":3,"ot":"Fevzi-Azbiye","pi":85},"4":{"aov":0,"oo":4,"ot":"Burak-Gizem","pi":86}}
我尝试了类似的东西,但没有希望:
function sortObject(o) {
var sorted = {},
key, a = [];
for (key in o) {
if (o.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = o[a[key]];
}
return sorted;
}
任何想法我该怎么做?
答案 0 :(得分:1)
正如其他人在评论中指出的那样,无法对对象的属性进行排序。您可以做的是生成对象属性的排序数组,并迭代该数组以按您希望的顺序访问对象属性。你基本上已经在你的示例代码中做了这个 - 你只是试着把它放得太远了。
function getObjectKeysAlphabetical(obj) {
var keys = [],
key;
for (key in obj) {
if (obj.hasOwnProperty(key))
keys.push(key);
}
keys.sort();
return keys;
}
var obj = {}; //Your object here.
var keys = getObjectKeysAlphabetical(obj)
i = 0, key = null, val = null;
//Iterate the array of sorted keys.
for (i = 0; i < keys.length; i++) {
key = keys[i];
val = obj[key]; //Get the value of the property here.
}