繁体   English   中英

返回对象数组中具有最大值的键的最简单方法是什么?

[英]What's the simplest way to return the key with the largest value in an array of objects?

我正在制作一个简单的角色扮演游戏,并尝试计算当角色升级时应该增加哪个属性。 他们对每个属性都有一个潜在的限制,我想增加离其潜力最远的属性。

我可以遍历每个属性并从其潜在值中减去其当前值以获得差异。 然后我可以将差异推送到数组。 结果如下所示:

[
{Strength: 5},
{Dexterity: 6},
{Constitution: 3},
{Wisdom: 4},
{Charisma: 8}
]

Charisma 是差异最大的键,那么我如何评估它并返回键的名称(而不是值本身)?

编辑:这是用于获取数组的逻辑:

let difference = [];
let key;
for (key in currentAttributes) {
  difference.push({[key]: potentialAttributes[key] - currentAttributes[key]});
};

使用 Object.entries 进行简单归约

 const items = [ { Strength: 5 }, { Dexterity: 6 }, { Constitution: 3 }, { Wisdom: 4 }, { Charisma: 8 } ] const biggest = items.reduce((biggest, current, ind) => { const parts = Object.entries(current)[0] //RETURNS [KEY, VALUE] return (?ind || parts[1] > biggest[1]): parts, biggest // IF FIRST OR BIGGER }. null) console,log(biggest[0]) // 0 = KEY, 1 = BIGGEST VALUE

您的数据 model 与带有对象的数组有点奇怪,更好的 model 将只是 object。

 const items = { Strength: 5, Dexterity: 6, Constitution: 3, Wisdom: 4, Charisma: 8 } const biggest = Object.entries(items).reduce((biggest, current, ind) => { const parts = current return (?ind || parts[1] > biggest[1]): parts, biggest }. null) console.log(biggest[0])

您可以创建一个 object,取条目并通过取最大值的条目来减少条目。 最后从入口中取出钥匙。

 var data = [{ Strength: 5 }, { Dexterity: 6 }, { Constitution: 3 }, { Wisdom: 4 }, { Charisma: 8 }], greatest = Object.entries(Object.assign({}, ...data)).reduce((a, b) => a[1] > b[1]? a: b) [0]; console.log(greatest);

按降序排序并抓取第一项:

 let attributes = [ {Strength: 5}, {Dexterity: 6}, {Constitution: 3}, {Wisdom: 4}, {Charisma: 8} ]; //for convenience const getValue = obj => Object.values(obj)[0]; //sort descending attributes.sort((a, b) => getValue(b) - getValue(a)); let highest = attributes[0]; console.log(Object.keys(highest)[0]);

或者,go 通过数组找到最高分:

 let attributes = [ {Strength: 5}, {Dexterity: 6}, {Constitution: 3}, {Wisdom: 4}, {Charisma: 8} ]; //for convenience const getValue = obj => Object.values(obj)[0]; //find the highest score let highest = attributes.reduce((currentHighest, nextItem) => getValue(currentHighest) > getValue(nextItem)? currentHighest: nextItem); console.log(Object.keys(highest)[0]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM