我有这两个功能,如果我分开它们,我会有很多冗余代码。你可以在这里看到它的作用https://jsfiddle.net/8m9zbefq/基本上我只是想转换数据结构。
如何将两个函数重构为一个?
const prepare_femaleObj = raw.map((obj, i) => {
const female_count = obj.age_data.reduce((accum, obj2) => {
if(obj2.female_count) return accum + obj2.female_count
}, 0)
const percentage = female_count / total_female_count * 100
return { id: ++i, camera: obj.device_info.name + ' - ' + obj.device_info.entrance_name, percentage }
})
const prepare_maleObj = raw.map((obj, i) => {
const male_count = obj.age_data.reduce((accum, obj2) => {
if(obj2.male_count) return accum + obj2.male_count
}, 0)
const percentage = male_count / total_male_count * 100
return { id: ++i, camera: obj.device_info.name + ' - ' + obj.device_info.entrance_name, percentage }
})
我有这个想法,使用模板文字来使性别动态
const prepare_Obj = (gender) => raw.map((obj, i) => {
const `${gender}_count` = obj.age_data.reduce((accum, obj2) => {
if(obj2[`${gender}_count`)] return accum + obj2.female_count
}, 0)
...
})
方法很好吗?