英文:
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: 'adsf...',
game1: 1,
game2: 2,
game3: 3,
game4: 4,
game5: 5,
game6: 6,
game7: 2,
name: 'xxx',
url: 'xxx',
city: 'xxx'
}
const gameTotal = Object.entries(obj1)
.reduce((total, [key, value]) => key.startsWith("game") ? total += value : total, 0);
console.log(gameTotal);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论