简体   繁体   中英

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. My Firestore collection contains data in the format of:

{
  '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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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