Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

326
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda