如何将json按数值排序到数组中,然后如何轻松访问该信息。
{"362439239671087109":{"coins":19},"178538363954003968":{"coins":18},"234255082345070592":{"coins":137}}
奇怪的数字是不和谐的用户ID。
答案 0 :(得分:0)
嗯。首先,创建关联数组,如果json是从bakcend生成的(例如在php中),则可以将函数用于订单数组。 ---> http://php.net/manual/en/array.sorting.php 看到这个: Converting JavaScript object with numeric keys into array
答案 1 :(得分:0)
var a = {"362439239671087109":{"coins":19},"178538363954003968":{"coins":18},"234255082345070592":{"coins":137}};
var b = Object.keys(a);
b.sort(function(x,y){return a[x].coins-a[y].coins});
console.log(b);
答案 2 :(得分:0)
// Code that can handle VERY large numbers by treating them as strings.
var a = {
"362439239671087109": {
"coins": 19
},
"178538363954003968": {
"coins": 18
},
"234255082345070592": {
"coins": 137
}
};
function padWithZeros(s) {
return ("000000000000000000000" + s).substr(-20);
}
var b = Object.keys(a);
b.sort(
function(x, y) {
var s1 = padWithZeros(a[x].coins);
var s2 = padWithZeros(a[y].coins);
if (s1 === s2) {
return 0;
}
if (s1 > s2) {
return 1;
} else {
return -1;
}
});
console.log(b);