我的对象如下:
players: {
p1: {
name: joe,
points: 25
},
p2: {
name: frank,
points: 35
},
p3: {
name: tim,
points: 55
}
}
如何返回具有最高“点数”值的玩家对象?例如:
{ name: tim, points: 55 }
答案 0 :(得分:2)
使用JavaScript Array#reduce
方法。
var data = {
players: {
p1: {
name: 'joe',
points: 25
},
p2: {
name: ' frank',
points: 35
},
p3: {
name: 'tim',
points: 55
}
}
};
var res = data.players[
// get all property names
Object.keys(data.players)
// get the property name which holds the hghest point
.reduce(function(a, b) {
// compare and get the property which holds the highest
return data.players[a].points < data.players[b].points ? b : a;
})
];
console.log(res);
&#13;
答案 1 :(得分:2)
使用_.maxBy
_.chain(players)
.values()
.maxBy('points')
.value();
答案 2 :(得分:0)
const data = {p1: {name: 'hello', points: 1}, p2: {name: 'world', points: 2}}
const dataList = _.values(data)
const maxPointItem = dataList.reduce((prev, curr) => prev.points < curr.points ? curr : prev), dataList[0])