js比较两个数组对象,取出key相同的并push进同一数组

首先我们来mock两个对象数组:

previousList = [
{
   dbtime: "02",
   e: 100,
   kk: 200
},{
   dbtime: "05",
   e: 20,
   kk: 100
}],currentList = [{
   dbtime: "02",
   e: 50,
   kk: 600
},{
   dbtime: "05",
   e: 120,
   kk: 700
},{
   dbtime: "11",
   e: 120,
   kk: 88
}];

然后进行匹配取值: 

// js比较两个数组对象,取出key相同的并push进同一数组
   let yearList = [];
   for(let i = 0; i < this.previousList.length; i++){
       let obj = this.previousList[i], num = obj.dbtime, flag = false;
       for(let j = 0; j < this.currentList.length; j++){
           let aj = this.currentList[j], n = aj.dbtime, yearObj = {};
           //如果detime对应匹配
           if(n == num){
             flag = true;
             yearObj["dbtime"] = num || n;
             yearObj["e1"] = obj.e;//过去
             yearObj["e2"] = aj.e;//当前
             yearList.push(yearObj);
           }else{
              flag = false;
           }
        }
    }

最后打印一下,看看结果:

  console.log(yearList);
    //打印最终的结果yearList
    yearList = [{
        dbtime: "02",
        e1: 50,
        e2: 100
    },{
        dbtime: "05",
        e1: 120,
        e2: 20
    }]

参考文档: 

1.JavaScript中for循环的效率对比

2.javascript – 一个for循环,用于比较两个查找匹配值的数组

你可能感兴趣的:(JavaScript)