javascript - ผลรวมทั้งหมดของค่าภายในวัตถุซ้อนในอาร์เรย์
วิธีหาผลรวมของค่าทั้งหมดของ stationuserAmount ในอาเรย์ที่ให้มา
"staions": [
{
"name": "Guwahati",
"stationuser": [
{
"name": "Suranjan Dey",
"stationuserAmount": "190"
}
]
},
{
"name": "Bhubaneshwar",
"stationuser": [
{
"name": "Soubhagya Behera",
"stationuserAmount": "280"
},
{
"name": "Om Prakash Sahoo",
"stationuserAmount": "280"
}
]
}
]
ฉันได้ลองใช้ map และ reduce กับค่าของอาเรย์เพื่อหาผลรวมทั้งหมดของอาเรย์ที่ให้มา
1) const salesuserTotalCount = this.state.staions.map(items => ({
users: items.stationuser.reduce((a, b) => {return
a.stationuserAmount+b.stationuserAmount}
)}))
2) const salesuserTotalCount = this.state.staions.map(items => ({
...items,
users: items.stationuser.map(stationitems
=>stationitems.stationuserAmount).reduce((a, c)
=> { return a + c })}))
คำตอบ #1
คุณสามารถทำ reduce ภายใน reduce ได้
const stations = [
{
"name": "Guwahati",
"stationuser": [
{
"name": "Suranjan Dey",
"stationuserAmount": 190
}
]
},
{
"name": "Bhubaneshwar",
"stationuser": [
{
"name": "Soubhagya Behera",
"stationuserAmount": 280
},
{
"name": "Om Prakash Sahoo",
"stationuserAmount": 280
}
]
}
]
console.log(stations.reduce((acc, curr)=>{
return acc+curr.stationuser.reduce((a,c)=>a+c.stationuserAmount,0)
},0));คำตอบ #2
คุณสามารถทำได้อย่างง่ายดายด้วยแผนที่ซ้อนกัน
const data = { "stations": [
{
"name": "Guwahati",
"stationuser": [
{
"name": "Suranjan Dey",
"stationuserAmount": 190
}
]
},
{
"name": "Bhubaneshwar",
"stationuser": [
{
"name": "Soubhagya Behera",
"stationuserAmount": 280
},
{
"name": "Om Prakash Sahoo",
"stationuserAmount": 280
}
]
}
]
}
let sum = 0
data.stations.map(station => {
station.stationuser.map(user => sum += user.stationuserAmount)
})
console.log(sum)