我有一个像这样的对象
{
"playerId1": {
"score": 100,
"rank": 0
},
"playerId2": {
"score": 500,
"rank": 0
},
"playerId3": {
"score": 200,
"rank": 0
}
}
,我需要根据得分对它们进行排序,然后分配排序的顺序进行排名。 最好的方法是什么?
我已经厌倦了转换为数组,然后排序很容易,但是我想保留Object结构。
答案 0 :(得分:2)
您可以设置等级并将其保留为对象。
var temp = {
"playerId1": {
"score": 100,
"rank": 0
},
"playerId2": {
"score": 500,
"rank": 0
},
"playerId3": {
"score": 200,
"rank": 0
}
};
Object.values(temp).sort(function(a, b){
return a.score - b.score;
}).forEach(function(player, rank){
player.rank = rank;
});
console.log(temp);
答案 1 :(得分:1)
使用一些排序,映射和归约,可以先解构然后再重建对象。
const obj = {
"playerId1": {
"score": 100,
"rank": 0
},
"playerId2": {
"score": 500,
"rank": 0
},
"playerId3": {
"score": 200,
"rank": 0
}
}
let r = Object.keys(obj)
.reduce((result, key) => {
let v = obj[key]
v['p'] = key
return result.concat(v)
}, [])
.sort((a, b) => b.score - a.score)
.map((itm, idx) => {itm.rank = idx + 1; return itm})
.reduce((result, itm) => {result[itm['p']] = itm; delete result[itm['p']]['p']; return result}, {})
console.log(r)
答案 2 :(得分:0)
您无法对对象进行排序。但是您可以保留对象,因为它是通过多种方式拉动排序后的数组的。例如,如果您只想要按排名排序的球员列表,则可以:
let obj = {"playerId1": {"score": 100,"rank": 0},"playerId2": {"score": 500,"rank": 3},"playerId3": {"score": 200,"rank": 2}}
let sortedPlayers = Object.keys(obj).sort((a, b) => obj[a].rank - obj[b].rank)
console.log(sortedPlayers)
或者您可以创建一个包含玩家和得分的数组:
let obj = {"playerId1": {"score": 100,"rank": 0},"playerId2": {"score": 500,"rank": 3},"playerId3": {"score": 200,"rank": 2}}
let sortedPlayers = Object.entries(obj).sort(([k1, v1], [k2, v2]) => v1.rank - v2.rank).map(([player, scores]) => ({player, scores}))
console.log(sortedPlayers)
这完全取决于您需要执行的操作以及所需的特定输出。