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