几个数组里的对象交叉合并

arr1: [
        { a: 1, b: 2 },
        { a: 3, b: 4 }
      ],
arr2: [
        { c: 5, d: 6 },
        { c: 7, d: 8 }
      ]
要求写成
[
{a: 1, b: 2, c: 5, d: 6},
{a: 1, b: 2, c: 7, d: 8},
{a: 3, b: 4, c: 5, d: 6},
{a: 3, b: 4, c: 7, d: 8},
]
 
methods:{
cartesianProduct(arr) {
      return arr.reduce((a, b) => a.map(x => b.map(y => x.concat(y))).reduce((a, b) => a.concat(b), []), [[]]).map(item => item.reduce((a, b) => { return { ...a, ...b } }, {}))
    },
getDatas(){
  this.cartesianProduct([this.arr1, this.arr2])
}
}
 
 
单数组交叉合并
function cartesianProduct(arr) { return arr.reduce((a, b) => a.map(x => b.map(y => x.concat(y))).reduce((a, b) => a.concat(b), []), [[]])}
使用
this.cartesianProduct([[1, 2, 3], ['a', 'b'], ['c']])
 
原文地址:https://www.cnblogs.com/hellofangfang/p/13683548.html