如何使用Javascript数组方法批量统计对象数组中多字段的真值出现次数
实现方案
你可以通过reduce配合map方法实现,只需要一次遍历即可完成所有字段统计,无需手动枚举每个f开头的字段:
const countMap = myArray.reduce((result, currentItem) => { Object.keys(currentItem).forEach(key => { // 匹配所有f+数字格式的字段,过滤非统计目标字段 if (/^f\d+$/.test(key)) { result[key] = (result[key] || 0) + (currentItem[key] ? 1 : 0) } }) return result }, {}) // 转换为你需要的chartData格式 const chartData = Object.entries(countMap).map(([field, count]) => ({ name: field.toUpperCase(), value: count }))
可选优化
如果你的f开头字段是固定范围(比如f1~f20),可以手动指定字段列表,避免匹配到意外的f开头字段,逻辑更可控:
// 生成f1到f20的字段列表 const statFields = Array.from({ length: 20 }, (_, index) => `f${index + 1}`) const countMap = myArray.reduce((result, currentItem) => { statFields.forEach(field => { result[field] = (result[field] || 0) + (currentItem[field] ? 1 : 0) }) return result }, {}) const chartData = Object.entries(countMap).map(([field, count]) => ({ name: field.toUpperCase(), value: count }))
该方案相比逐个字段filter的写法,时间复杂度从O(n*m)(n为数组长度,m为f字段数量)降到了O(n),数据量越大性能优势越明显,且后续新增f开头的统计字段也无需修改代码。
内容的提问来源于stack exchange,提问作者Codshark11
相关产品推荐
相关产品推荐

