两对象值合并

需求:改变数据结构

let originArr =  [
{
"hourId": 0, 
"costRate": 0.001,
...
},
{
"hourId": 1, 
"costRate": 0.001,
...
}
]



let compareArr =  [
{
"hourId": 0, 
"costRate": 0.001,
...
},
{
"hourId": 1, 
"costRate": 0.001,
...
}
]


console.log(merge(originArr, compareArr))  //


[
{
"hourId": 0, 
"costRate":{

  start:0.01,

  compare: 0.2

},
...
},


{
"hourId": 1, 

"costRate":{

  start:0.01,

  compare: 0.2

},

...
}
]

 
  merge = (originArr, compareArr) => {
    let keyArr = Object.keys(originArr[0])
    let newArr = []
    for (let k = 0; k < originArr.length; k++) {
      let obj = {}
      for (let i = 0; i < keyArr.length; i++) {
        if (keyArr[i] === 'hourId') {
          obj[keyArr[i]] = originArr[k][keyArr[i]]
        } else {
          obj[keyArr[i]] = {
            start: originArr[k][keyArr[i]],
            compare: compareArr[k][keyArr[i]],
          }
        }
      }
      newArr.push(obj)
    }
    return newArr
  }

 

posted @ 2018-08-13 09:55  doublealoe  阅读(130)  评论(0编辑  收藏  举报