[英]Get sum from the nested array of objects
我有以下对象数组。 如您所见,每个对象中都有一个名为count
的嵌套 object。 我想获得Closed
、 Verify
和Analyze
的总数
例如, Closed
的总数为 23, Verify
为 3, Analyze
为 20
"byPerson": [
{
"personId": "973567318",
"firstName": "Others",
"lastName": "",
"count": {
"Closed": 7,
"Verify": 3,
"Analyze": 19
}
},
{
"personId": "1514903899",
"firstName": "Yatish",
"lastName": "Patel",
"count": {
"Closed": 16,
"Analyze": 1
}
}
]
我尝试过这种方式,但没有奏效。 例如,获得Closed
的总数
cosnt result = data.reduce((a, b) => ({"Closed": a.count["Closed"] + b.count["Closed"]}));
const byPerson = [ { "personId": "973567318", "firstName": "Others", "lastName": "", "count": { "Closed": 7, "Verify": 3, "Analyze": 19 } }, { "personId": "1514903899", "firstName": "Yatish", "lastName": "Patel", "count": { "Closed": 16, "Analyze": 1 } } ]; const sum = byPerson.reduce((agg, item) => { ['Closed', 'Verify', 'Analyze'].forEach(f => agg[f] += item.count[f] || 0); return agg; }, {Closed: 0, Verify: 0, Analyze: 0}); console.log(sum);
将数据减少到 object 中,其中包含您想要总计的嵌套属性的键。 在 reduce 回调中,解构“totals”属性和嵌套的count
属性并计算总和。
const data = [ { "personId": "973567318", "firstName": "Others", "lastName": "", "count": { "Closed": 7, "Verify": 3, "Analyze": 19 } }, { "personId": "1514903899", "firstName": "Yatish", "lastName": "Patel", "count": { "Closed": 16, "Analyze": 1 } } ]; const totalCount = data.reduce(({ Closed, Analyze, Verify }, { count }) => ({ Closed: Closed + (count?.Closed || 0), Analyze: Analyze + (count?.Analyze || 0), Verify: Verify + (count?.Verify || 0), }), { Closed: 0, Analyze: 0, Verify: 0, }); console.log(totalCount);
在这种情况下,您甚至不需要 reduce 并且可以使用简单的循环以及迭代Object.keys()
const byPerson = [ { "personId": "973567318", "firstName": "Others", "lastName": "", "count": { "Closed": 7, "Verify": 3, "Analyze": 19 } }, { "personId": "1514903899", "firstName": "Yatish", "lastName": "Patel", "count": { "Closed": 16, "Analyze": 1 } } ]; const sum = {Closed: 0, Verify: 0, Analyze: 0} byPerson.forEach(({count})=> { Object.keys(sum).forEach(k => sum[k] += (count[k] || 0)) }); console.log(sum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.