假设我有以下数据
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"
}
]
}
];并在开头的对象变量下面
let typeTotalScore = {
communication: 0,
delivery: 0
};和useState钩子
const [scoreByType, setScoreByType] = useState({});我想循环遍历data并得到下面的结果,然后使用setScoreByType(typeTotalScore)。
{
communication: 6,
delivery: 8
}我应该如何在useEffect中做到这一点?
useEffect(() => {
async function fetchData() {
let typeTotalScore = {
communication: 0,
delivery: 0
};
// some looping?
setScoreByType(typeTotalScore)
}
fetchData();
}, []);发布于 2021-08-15 07:59:49
您可以使用Array#flatMap将所有分数数组合并为一个。然后使用Array#reduce对该值求和。
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)
https://stackoverflow.com/questions/68789670
复制相似问题