var leaderboard = [{userId: 10293, balance: 1023},
{userId: 20394, balance: 1806},
{userId: 45333, balance: 2064},
{userId: 57456, balance: 2453},
{userId: 24575, balance: 2703}
];
我有这个对象,想要创建一个函数,通过检查所有 userId
来搜索用户是否已添加。如果它们确实存在,我想将其特定余额更新为新的,在我的例子中,它将是 msg.userBalance
。如果它们不存在,我想检查它们的余额是否大于对象中当前的任何一个余额,如果是,我想将它们添加到对象中,并删除余额最低的第 6 个余额。
leaderboard.map(function(person) {
if (person.userId == msg.userId) {
person.balance = msg.userBalance
} else {
if (currentBalance > //other 5 balances in object {
leaderboard.push({userId: msg.userId, balance: msg.userBalance});
}
}
});
我有点卡住了,我知道我的方向是正确的,但显然错过了方程式的很大一部分。我并不反对使用 jQuery 我只是在寻找最简单的解决方案。帮忙?
最佳答案
我认为这会做你想要的,,
var user = leaderboard.filter(function(user){return userId == msg.userId})[0];
if(user){
user.balance = msg.userBalance;
} else {
leaderboard.push({userId: msg.userId, balance: msg.userBalance});
leaderboard.sort(function(a,b){return a.balance-b.balance});
leaderboard.shift();
}
我在这里所做的是,,我使用过滤器来获取与您的目标用户ID匹配的用户,, 如果没有找到,,我将其添加到数组中,,然后对数组进行升序排序,,然后删除第一个元素,,这将是最低的元素
关于javascript - 我有一个 javascript 对象,我想通过 id 查找用户并更新他们的余额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529011/