算法/挑战。我想计算所有游戏。

huangapple go评论65阅读模式
英文:

Algorithm / challenge . I want to calculate all games

问题

I have data/teams in mongodb. Each team has 11 items:

One object looks like this. I would like to calculate only games together.
But I have 8 objects! All games from obj1 + all games from obj2 + ...
All games from each obj together.

Can you find better solutions like obj1.game1 + obj1.game2 + ... obj2.game1 + ...

THANK YOU

_id: 'adsf...',
game1: 1,
game2: 2,
game3: 3,
game4: 4,
game5: 5,
game6: 6,
game7: 2,
name: 'xxx,
url: 'xxx',
city: 'xxx'
英文:

I have data/teams in mongodb. Each team has 11 items:

One object looks like this. I would like to calculate only games together.
But I have 8 objects! All games from obj1 + all games from obj2 + ...
All games from each obj together.

Can you find better solutions like obj1.game1 + obj1.game2 + ... obj2.game1 + ...

THANK YOU


_id: 'adsf...',
game1: 1,
game2: 2,
game3: 3,
game4: 4,
game5: 5,
game6: 6,
game7: 2,
name: 'xxx,
url: 'xxx',
city: 'xxx'

答案1

得分: 1

你可以使用 Object.entries() 获取对象的所有键值对,然后使用 reduce() 来计算所有具有以 game 开头的键的值的总和。

> 如果你想要更精确地匹配属性名称并避免匹配类似 gameDay 的内容,你也可以使用一些正则表达式。

英文:

You can use Object.entries() to get all key-value pairs of the object and then use reduce() to sum up all the values that have a key starting with game.

> You could also use some regex if you want a more precise match of the property name and want to avoid matching something like gameDay.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const obj1 = {
    _id: &#39;adsf...&#39;,
    game1: 1,
    game2: 2,
    game3: 3,
    game4: 4,
    game5: 5,
    game6: 6,
    game7: 2,
    name: &#39;xxx&#39;,
    url: &#39;xxx&#39;,
    city: &#39;xxx&#39;
}

const gameTotal = Object.entries(obj1)
    .reduce((total, [key, value]) =&gt; key.startsWith(&quot;game&quot;) ? total += value : total, 0);
console.log(gameTotal);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月7日 06:28:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定