我正在尝试排序一个不和谐机器人显示前3名成员。然而,我一直得到错误:
JavaScript错误:Uncaught TypeError: guildStats.slice
这是我尝试过的:
var guildStats = {
'1234567': {
xp: 95,
level: 0,
last_message: 1631181685724,
invited: {},
invited_by: 0
},
'0987654': {
xp: 13,
level: 0,
last_message: 1631181527799,
invited: {},
invited_by: 0
},
'243562345': {
xp: 18,
level: 0,
last_message: 1631181537020,
invited: {},
invited_by: 0
},
'76533465': {
xp: 14,
level: 0,
last_message: 1631181536875,
invited: {},
invited_by: 0
},
'34667634567': {
xp: 8,
level: 0,
last_message: 1631181659142,
invited: {},
invited_by: 0
},
'346534': {
xp: 98,
level: 0,
last_message: 1631181638743,
invited: {},
invited_by: 0
},
'34343677677886': {
xp: -63,
level: 0,
last_message: 1631181584314,
invited: {},
invited_by: 0
},
'987654345676543': {
xp: 20,
level: 0,
last_message: 1631181589153,
invited: {},
invited_by: 0
},
'75634576786588': {
xp: -140,
level: 0,
last_message: 1631181593304,
invited: {},
invited_by: 0
},
'34343434556566': {
xp: 43,
level: 0,
last_message: 1631181663340,
invited: {},
invited_by: 0
}
};
var byXP = guildStats.slice(0);
byXP.sort(function(a,b) {
return a.xp - b.xp;
});
document.write(byXP);
我想输出的是
The top 3 members by XP are:
1. 346534
2. 1234567
3. 34343434556566
我知道我哪里搞砸了。
如何按子对象键xp的值对guildStats
中的所有对象进行排序
谢谢你的帮助。
您可以使用Object.fromEntries()
将您的对象转换为[键,值]对的数组。
然后我们可以对xp进行排序,并使用Array.slice()
返回前三个条目。
var guildStats = { '1234567': { xp: 95, level: 0, last_message: 1631181685724, invited: {}, invited_by: 0 }, '0987654': { xp: 13, level: 0, last_message: 1631181527799, invited: {}, invited_by: 0 }, '243562345': { xp: 18, level: 0, last_message: 1631181537020, invited: {}, invited_by: 0 }, '76533465': { xp: 14, level: 0, last_message: 1631181536875, invited: {}, invited_by: 0 }, '34667634567': { xp: 8, level: 0, last_message: 1631181659142, invited: {}, invited_by: 0 }, '346534': { xp: 98, level: 0, last_message: 1631181638743, invited: {}, invited_by: 0 }, '34343677677886': { xp: -63, level: 0, last_message: 1631181584314, invited: {}, invited_by: 0 }, '987654345676543': { xp: 20, level: 0, last_message: 1631181589153, invited: {}, invited_by: 0 }, '75634576786588': { xp: -140, level: 0, last_message: 1631181593304, invited: {}, invited_by: 0 }, '34343434556566': { xp: 43, level: 0, last_message: 1631181663340, invited: {}, invited_by: 0 } };
var byXP = Object.entries(guildStats);
byXP.sort(function([keya,valuea],[keyb,valueb]) {
return valueb.xp - valuea.xp;
});
console.log('The top 3 members by XP are:');
byXP.slice(0,3).forEach(([key, member],idx) => console.log(`${idx+1}. ${key}, xp: ${member.xp}`));