Home > other >  Is it possible to filter key value pairs based on a section of the key?
Is it possible to filter key value pairs based on a section of the key?

Time:12-13

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.

CodePudding user response:

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

  • Related