Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

323
Views
React - what is the right way to sum the value of object by its type and then setState

Let's say I have below data

  const data = [
    {
      id: 1,
      name: "Tim",
      score: [
        {
          score: 4,
          type: "communication"
        },
        {
          score: 4,
          type: "delivery"
        }
      ]
    },
    {
      id: 2,
      name: "Ken",
      score: [
        {
          score: 2,
          type: "communication"
        },
        {
          score: 4,
          type: "delivery"
        }
      ]
    }
  ];

and below object variable at the beginning

      let typeTotalScore = {
        communication: 0,
        delivery: 0
      };

and useState hook

  const [scoreByType, setScoreByType] = useState({});

I want to loop through data and get below result and then use setScoreByType(typeTotalScore).

{
  communication: 6,
  delivery: 8
}

How should I do it in useEffect

  useEffect(() => {
    async function fetchData() {
      let typeTotalScore = {
        communication: 0,
        delivery: 0
      };

     // some looping?

     setScoreByType(typeTotalScore)
    }
    fetchData();
  }, []);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use Array#flatMap combine all score array into one. Then use Array#reduce for sum the value

const data = [ { id: 1, name: "Tim", score: [ { score: 4, type: "communication" }, { score: 4, type: "delivery" } ] }, { id: 2, name: "Ken", score: [ { score: 2, type: "communication" }, { score: 4, type: "delivery" } ] } ];


const res =  data.flatMap(a=> a.score).reduce((acc,{type,score})=>{
   acc[type] = acc[type] || 0; //check the key and assigning the value 
   acc[type] = acc[type] + score // sum the previous score with new
   return acc
},{})

console.log(res)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!