// knew payloads
let data = [{name:'离职',label:'quit'},{name:'在职',label:'on'}]
let rows = [ {month: 1,quit:2,on:10}, {month: 2,quit:1,on:11}, {month: 3,quit:3,on:9} ]
// static parameters
const monthList = ['January','February','March','April']
// solution A
let res1 = data.map(ele=>{
let temp = { name:ele.name }
rows.forEach(item=>{
if ( monthList[(item.month)-1] ) temp[monthList[(item.month)-1]] = item[ele.label] || 0
})
return temp
})
// solution B
class counter {
constructor({name}) {
this.months = ['January','February','March','April']
this.zeorParma = {}
this.months.forEach(m=>{
this.zeorParma[m] = 0
})
this.name = name
}
// transfer with int
countInt(list,label) {
let res = { name : this.name, ...this.zeorParma }
list.forEach(ele=>{
if(this.months[ele.month-1]){
res[this.months[ele.month-1]] = ele[label] || 0
}
})
return res
}
// transfer with percent
countPercent(list,label,adders){
let res = { name : this.name, ...this.zeorParma }
list.forEach(ele=>{
if(this.months[ele.month-1]){
let sum = adders.reduce((total,cur)=>total + (ele[cur] || 0) ,0)
res[this.months[ele.month-1]] = (ele[label] / sum).toFixed(2)
}
})
return res
}
}
let res2 = data.map(ele=>{
return new counter(ele).countInt(rows,ele.label)
})
let res3 = data.map(ele=>{
return new counter(ele).countPercent(rows,ele.label,data.map(e=>e.label))
})
console.log(res1,res2,res3)
输出
[
{ name: '离职', January: 2, February: 1, March: 3 },
{ name: '在职', January: 10, February: 11, March: 9 }
] [
{ name: '离职', January: 2, February: 1, March: 3, April: 0 },
{ name: '在职', January: 10, February: 11, March: 9, April: 0 }
] [
{
name: '离职',
January: '0.17',
February: '0.08',
March: '0.25',
April: 0
},
{
name: '在职',
January: '0.83',
February: '0.92',
March: '0.75',
April: 0
}
]