猿问

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

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


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


[

{Strength: 5},

{Dexterity: 6},

{Constitution: 3},

{Wisdom: 4},

{Charisma: 8}

]

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


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


let difference = [];

let key;

for (key in currentAttributes) {

  difference.push({[key]: potentialAttributes[key] - currentAttributes[key]});

};


Qyouu
浏览 195回答 3
3回答

30秒到达战场

使用 Object.entries 进行简单的 reduceconst 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您的数据模型对于带有对象的数组有点奇怪,更好的模型只是一个对象。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])

12345678_0001

您可以创建一个对象,获取条目并通过获取具有最大值的条目来减少条目。最后从入口拿钥匙。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);

SMILET

按降序排序并获取第一项:let attributes = [  {Strength: 5},  {Dexterity: 6},  {Constitution: 3},  {Wisdom: 4},  {Charisma: 8}];//for convenienceconst getValue = obj => Object.values(obj)[0];//sort descendingattributes.sort((a, b) => getValue(b) - getValue(a));let highest = attributes[0];console.log(Object.keys(highest)[0]);或者,遍历数组并找到最高分:let attributes = [  {Strength: 5},  {Dexterity: 6},  {Constitution: 3},  {Wisdom: 4},  {Charisma: 8}];//for convenienceconst getValue = obj => Object.values(obj)[0];//find the highest scorelet highest = attributes.reduce((currentHighest, nextItem) => getValue(currentHighest) > getValue(nextItem) ?  currentHighest : nextItem);console.log(Object.keys(highest)[0]);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答