Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

js怎么根据月份把两个数组对象整合为一个新的数组对象?

各位大佬,怎么才能把这两个数组整合为下面这种数组的形式?

var data = [
    {name:'离职',label:'quit'},{name:'在职',label:'on'}
];
var rows = [
    {month: 1,quit:2,on:10},
    {month: 2,quit:1,on:11},
    {month: 3,quit:3,on:9}
];
结果: [
     {name: '离职',January: 2,February: 1,March: 3},
     {name: '在职',January: 10,February: 11,March: 9}
 ];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
//  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
  }
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...