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

Viewed 80

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();
  }, []);
1 Answers

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)

Related