首页 > 解决方案 > 用三个键合并数组对象

问题描述

有两个对象数组,a 和 b。键是'id','isfix','groupid'。

例如

a.id === b.id && a.isfix === b.isfix &&  a.groupid===b.groupdid

序列数组不一样。

我期待c。

我希望你不要使用 lodash。我喜欢 es6 或 vanila js。谢谢..

我认为减少、映射和过滤.. 但不如我想的那么好。我认为make函数...输入是a,b,输出是c

var a = [
  {
    id:"555",
    groupID:"10",
    isFix:false,
    tolerancePlus:5,
    toleranceMinus:3
  },
  {
    id:"123",
    groupID:"10",
    isFix:true,
    tolerancePlus:"",
    toleranceMinus:7
  },
  {
    id:"555",
    groupID:"10",
    isFix:true,
    tolerancePlus:11,
    toleranceMinus:6
  }
]

var b =  [
  {
    id:"123",
    groupID:"10",
    isFix:true,
    tolerance:{
      min: null,
      plus : null
    }
  },
  {
    id:"555",
    groupID:"10",
    isFix:false,
    tolerance:{
      min: null,
      plus : null
    }
  },
  {
    id:"555",
    groupID:"10",
    isFix:true,
    tolerance:{
      min: null,
      plus : null
    }
  },
]

var c =  [
  {
    id:"123",
    groupID:"10",
    isFix:true,
    tolerance:{
      min: 7,
      plus : 0 // if "" that value is 0
    }
  },
  {
    id:"555",
    groupID:"10",
    isFix:false,
    tolerance:{
      min: 3,
      plus : 5
    }
  },
  {
    id:"555",
    groupID:"10",
    isFix:true,
    tolerance:{
      min: 6,
      plus : 11
    }
  },
]

标签: javascriptarraysobjectmerge

解决方案


这是香草JS中的逻辑:

var a = [
  {
    id: '555',
    groupID: '10',
    isFix: false,
    tolerancePlus: 5,
    toleranceMinus: 3
  },
  {
    id: '123',
    groupID: '10',
    isFix: true,
    tolerancePlus: '',
    toleranceMinus: 7
  },
  {
    id: '555',
    groupID: '10',
    isFix: true,
    tolerancePlus: 11,
    toleranceMinus: 6
  }
]
var b = [
  {
    id: '123',
    groupID: '10',
    isFix: true,
    tolerance: {
      min: null,
      plus: null
    }
  },
  {
    id: '555',
    groupID: '10',
    isFix: false,
    tolerance: {
      min: null,
      plus: null
    }
  },
  {
    id: '555',
    groupID: '10',
    isFix: true,
    tolerance: {
      min: null,
      plus: null
    }
  }
]

var c = a.map(data1 => {
  const toleranceData = b.map(data2 => {
    if (
      data1.id === data2.id &&
      data1.isfix === data2.isfix &&
      data1.groupdid === data2.groupdid
    ) {
      return {
        tolerance: {
          min: data1.toleranceMinus || 0,
          plus: data1.tolerancePlus || 0
        }
      }
    }
  })
  const { tolerance } = toleranceData.filter(d => d)[0]
  const { id, groupID, isFix } = data1
  return { id, groupID, isFix, tolerance }
})

console.log(c)


推荐阅读