Reputation: 956
My object looks like this:
players: {
p1: {
name: joe,
points: 25
},
p2: {
name: frank,
points: 35
},
p3: {
name: tim,
points: 55
}
}
How would I return the player object with the highest "points" value? For example:
{ name: tim, points: 55 }
Upvotes: 2
Views: 410
Reputation: 7416
use _.maxBy
_.chain(players)
.values()
.maxBy('points')
.value();
Upvotes: 2
Reputation: 2284
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])
Upvotes: 0
Reputation: 115242
Use JavaScript Array#reduce
method.
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);
Upvotes: 2