我有这个对象数组,我需要按照得分的降序对“列表”和“得分”进行排序。
var list =[{ '440684023463804938': { score: 6, bonuscount: 2 },
'533932209300832266': { score: 20, bonuscount: 0 },
'448746017987231756': { score: 9, bonuscount: 0 },
'492585498561216513': { score: 14, bonuscount: 0 } }]
我通常使用.sort函数,但这一次它给了我list.sort不是一个函数
感谢您的帮助。
答案 0 :(得分:2)
您可以将对象转换为数组,然后进行常规排序:
const list = [
{
'440684023463804938': {score: 6, bonuscount: 2},
'533932209300832266': {score: 20, bonuscount: 0},
'448746017987231756': {score: 9, bonuscount: 0},
'492585498561216513': {score: 14, bonuscount: 0}
}
];
const result = Object.entries(list[0]).sort((a, b) => b[1].score - a[1].score);
console.log(result);
答案 1 :(得分:1)
如果要保留JSON体系结构,请从输入内容开始:
const input = [{ '440684023463804938': { score: 6, bonuscount: 2 },
'533932209300832266': { score: 20, bonuscount: 0 },
'448746017987231756': { score: 9, bonuscount: 0 },
'492585498561216513': { score: 14, bonuscount: 0 } }];
const output = Object.keys(input[0]).sort((a,b) => b-a)
.reduce( (acc , curr) => {
acc[curr] = input[0][curr];
return acc;
},
{});
console.log([output]);