javascript - 遍历此对象的最佳方法是什么?
问题描述
我被困在循环一个名为Players
包含玩家数据的对象中。我想检查哪个玩家的x
价值最高,并将其保存在leader
变量中,该变量会在其他玩家具有更高的x
价值时发生变化。
对象如下所示:
var players = {
'86wjIB7Xbz1tmwlTAAAB': {
rotation: 0.09999999999999964,
x: 579,
y: 579,
playerId: '86wjIB7Xbz1tmwlTAAAB'
},
'dWwtnOI8PryXJNDWAAAC': {
rotation: 0.09999999999999964,
x: 488,
y: 579,
playerId: 'dWwtnOI8PryXJNDWAAAC'
},
'GZPYpWdrzj9x0-SsAAAD': {
rotation: -0.09999999999999964,
x: 694,
y: 579,
playerId: 'GZPYpWdrzj9x0-SsAAAD'
}
}
这就是我希望输出的样子
leader = GZPYpWdrzj9x0;
解决方案
请使用 Object.keys
var players = {
'86wjIB7Xbz1tmwlTAAAB': {
rotation: 0.09999999999999964,
x: 579,
y: 579,
playerId: '86wjIB7Xbz1tmwlTAAAB'
},
dWwtnOI8PryXJNDWAAAC: {
rotation: 0.09999999999999964,
x: 488,
y: 579,
playerId: 'dWwtnOI8PryXJNDWAAAC'
},
'GZPYpWdrzj9x0-SsAAAD': {
rotation: -0.09999999999999964,
x: 694,
y: 579,
playerId: 'GZPYpWdrzj9x0-SsAAAD'
}
}
const leader = Object.keys(players).reduce((acc, cur) => {
const obj = players[cur];
return acc.x < obj.x ? { x:obj.x, leader: obj.playerId } : acc;
}, { x: 0, leader: "" });
console.log(leader);
推荐阅读
- python - Selenium + Firefox + Python:下载目录问题
- java - 如何在休眠查询中使字符串不区分大小写?
- python-3.x - 使用 urllib 发布请求时获取 HTTP 400 错误请求
- r - 过滤唯一行忽略 NA
- amazon-web-services - 访问雪花文件系统
- android - setOnCreateContextMenuListener 在 RecycleView OnBindViewHolder 中不起作用
- html - 选择mat-option(角度)时如何调用方法?
- sql-server - 为什么由于缺少“下一个使用的文件组”而无法重新分区我的 SQL Server 表?
- python - 如何在python selenium中将文本框数据转换为整数
- ubuntu - 无法找到软件包 gluu-server