gpt4 book ai didi

javascript - 如何返回具有最大键 :value using lodash? 的嵌套对象

转载 作者:行者123 更新时间:2023-11-29 17:53:41 26 4
gpt4 key购买 nike

我的对象看起来像这样:

players: {
p1: {
name: joe,
points: 25
},
p2: {
name: frank,
points: 35
},
p3: {
name: tim,
points: 55
}
}

如何返回具有最高“点”值的玩家对象?例如:

{ name: tim, points: 55 }

最佳答案

使用 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);

关于javascript - 如何返回具有最大键 :value using lodash? 的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41114515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com