[英]Is it possible to filter key value pairs based on a section of the key?
I am building a react app with Firebase back end.我正在构建一个后端为 Firebase 的 React 应用程序。 My Firestore collection contains data in the format of:
我的 Firestore 集合包含以下格式的数据:
{
'Title One': 'The Title Here',
'Title One Score': '23',
'Title Two': 'The Second Title Here',
'Title Two Score': '43',
'Title Three': 'The Third Title Here',
'Title Three Score': '65',
}
I would like to filter out all the fields that end with the 'Score' and then add up all the values of the score.我想过滤掉所有以“分数”结尾的字段,然后将分数的所有值相加。 Like in that case, I would get 131.
就像那样,我会得到 131。
I was trying along these lines but didn't know how to proceed我正在尝试沿着这些路线但不知道如何进行
const totalScore = Object.entries(datasets)
.filter(([key, value]) => [
'Score'
].includes(key))
.sort()
.map(pair => {
const key = pair[0]
const value = pair[1]
//GET THE TOTAL SCORES HERE
return(
// <h2>{ TOTAL SCORE }</h2>
)
})
Does any one know how to do that?有谁知道这是怎么做到的吗? Please help.
请帮忙。
Thanks.谢谢。
You could get the entries and check the key for the wanted ending.您可以获得条目并检查所需结尾的密钥。 If it has the wanted ending add the value or take zero for getting a total value.
如果它有想要的结局,则添加该值或取零以获得总值。
const data = { 'Title One': 'The Title Here', 'Title One Score': '23', 'Title Two': 'The Second Title Here', 'Title Two Score': '43', 'Title Three': 'The Third Title Here', 'Title Three Score': '65' }, total = Object.entries(data).reduce((t, [k, v]) => t + (k.endsWith(' Score')? +v: 0), 0); console.log(total);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.