两对象值合并
Posted aloehui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两对象值合并相关的知识,希望对你有一定的参考价值。
需求:数据结构变化
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 }
以上是关于两对象值合并的主要内容,如果未能解决你的问题,请参考以下文章