如果两个数组中的键值匹配,如何组合两个数组对象

时间:2016-10-03 22:39:42

标签: javascript jquery arrays merge javascript-objects

我正在尝试根据航班键将两个数组对象与不同的数组对象组合在一起 如果值在a2中匹配,我想将其与a1合并并创建新数组 a1中的所有数据都必须在那里,并且必须将匹配的航班详细信息从a2添加到a1
请帮我解决这个问题。

a1 = [{'flight':'AF1223','oring':'CDF', 'Dest':'HNG'},{'flight':'XG23','oring':'HYD', 'Dest':'MMZ'},{'flight':'PK145','oring':'XYZ', 'Dest':'PEK'}]

a2 = [{'price':230,'avail':20,'flight':'AF1223'}, {'price':430,'avail':30,'flight':'DF43'},{'price':430,'avail':30,'flight':'XG23'} ]

combine array = [{'flight':'AF1223','oring':'CDF', 'Dest':'HNG','price':230,'avail':20},{'flight':'XG23','oring':'HYD', 'Dest':'MMZ'},{'flight':'PK145','oring':'XYZ', 'Dest':'PEK','price':430,'avail':30,}]

3 个答案:

答案 0 :(得分:1)

你可以迭代两个数组,如果匹配来自array2 ito array1的push对象,就像..

var a1 = [{'flight':'AF1223','oring':'CDF', 'Dest':'HNG'},{'flight':'XG23','oring':'HYD', 'Dest':'MMZ'},{'flight':'PK145','oring':'XYZ', 'Dest':'PEK'}];

var a2 = [{'price':230,'avail':20,'flight':'AF1223'}, {'price':430,'avail':30,'flight':'DF43'},{'price':430,'avail':30,'flight':'XG23'} ];

var result = a1.slice(0);

for (var i = 0 ; i < result.length ; i++){
  for (var j = 0; j < a2.length ; j++){
    if (result[i].flight == a2[j].flight){
      result[i].price = a2[j].price;
      result[i].avail = a2[j].avail;
    }
  };  
};
console.log(result);

答案 1 :(得分:1)

我正在给你一个完整的解决方案。

a = [
  {'id':'A','oring':'CDF', 'Dest':'HNG'},
  {'id':'B','oring':'HYD', 'Dest':'MMZ'},
  {'id':'C','oring':'XYZ', 'Dest':'PEK'}];

b = [
  {'id':'A','price':230,'avail':20,}, 
  {'id':'D','price':430,'avail':30},
  {'id':'B','price':430,'avail':30} ];

// put the object D into array a
for(var i=0;i<b.length;i++) {
  var idb = b[i].id;
  var idnotfound = true;
  a.forEach(function(rowofa) {
    var ida = rowofa.id;
    if(ida == idb) {
      idnotfound = false;
    }
  });
  if(idnotfound){
    a.push(b[i]);
  }
}//for
//console.log('aa=>>',a);
//.......................................

//Match ids and then put all in array a

for(var i= 0;i<a.length;i++) {
  var ida = a[i].id;
  for(var j=0;j<b.length;j++) {
    var idb = b[j].id;
    if(ida == idb) {
      a[i].avail = b[j].avail;
      a[i].price = b[j].price;
    }//if
  } //for2
}//for1
console.log('aa=>',a);

输出

aa=> [ { id: 'A', oring: 'CDF', Dest: 'HNG', avail: 20, price: 230 },
       { id: 'B', oring: 'HYD', Dest: 'MMZ', avail: 30, price: 430 },
       { id: 'C', oring: 'XYZ', Dest: 'PEK' },
       { id: 'D', price: 430, avail: 30 } ]

答案 2 :(得分:0)

要匹配您想要的输出,您可以执行以下操作;

var a1 = [{'flight':'AF1223','oring':'CDF', 'Dest':'HNG'},{'flight':'XG23','oring':'HYD', 'Dest':'MMZ'},{'flight':'PK145','oring':'XYZ', 'Dest':'PEK'}],
    a2 = [{'price':230,'avail':20,'flight':'AF1223'}, {'price':430,'avail':30,'flight':'DF43'},{'price':430,'avail':30,'flight':'XG23'}],
result = a2.reduce((p,c) => (p[c.flight] && (p[c.flight] = Object.assign(p[c.flight],c)),p), a1.reduce((f,s) => (f[s.flight] = s,f),{}));
console.log(result);