首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React -将object的值与其类型相加然后再计算setState的正确方法是什么?

React -将object的值与其类型相加然后再计算setState的正确方法是什么?
EN

Stack Overflow用户
提问于 2021-08-15 07:53:42
回答 1查看 52关注 0票数 1

假设我有以下数据

代码语言:javascript
运行
复制
  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"
        }
      ]
    }
  ];

并在开头的对象变量下面

代码语言:javascript
运行
复制
      let typeTotalScore = {
        communication: 0,
        delivery: 0
      };

和useState钩子

代码语言:javascript
运行
复制
  const [scoreByType, setScoreByType] = useState({});

我想循环遍历data并得到下面的结果,然后使用setScoreByType(typeTotalScore)

代码语言:javascript
运行
复制
{
  communication: 6,
  delivery: 8
}

我应该如何在useEffect中做到这一点?

代码语言:javascript
运行
复制
  useEffect(() => {
    async function fetchData() {
      let typeTotalScore = {
        communication: 0,
        delivery: 0
      };

     // some looping?

     setScoreByType(typeTotalScore)
    }
    fetchData();
  }, []);
EN

回答 1

Stack Overflow用户

发布于 2021-08-15 07:59:49

您可以使用Array#flatMap将所有分数数组合并为一个。然后使用Array#reduce对该值求和。

代码语言:javascript
运行
复制
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)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68789670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档