如何在javascript中合并具有不同结构的两个对象

时间:2016-10-03 17:29:05

标签: javascript jquery arrays json javascript-objects

我有两个具有不同结构的对象,尝试将这两个对象与基于键值的匹配数据合并,并使用object1和object2中的完整数据创建一个新对象。

我的对象1

{  
   "schedule":{  
      "onward":{  
         "journey":[  
            {  
               "trips":[  
                  {  
                     "origin":{  
                        "airportCode":"AMS"
                     },
                     "destination":{  
                        "airportCode":"BCN"
                     },
                     "FlightNumber":"KL1665"
                  }
               ]
            },
            {  
               "trips":[  
                  {  
                     "origin":{  
                        "airportCode":"AMS"
                     },
                     "destination":{  
                        "airportCode":"BCN"
                     },
                     "FlightNumber":"MF9343"
                  }
               ]
            }
         ]
      }
   }
}

对象2

{  
   "flights":[  
      {  
         "flightNumber":"KL1665",
         "price":223,
         "available":10
      },
      {  
         "flightNumber":"KL112",
         "price":223,
         "available":10
      },
      {  
         "flightNumber":" KL112",
         "price":223,
         "available":10
      }
   ]
}

我想合并"价格"和"可用"与#34; flightNumber"匹配的对象并使用所有数据创建一个新对象。

我曾尝试使用loadash和下划线但无法想象。帮助会很棒,谢谢你。

1 个答案:

答案 0 :(得分:2)

2简单forEach会这样做: -

flights.flights.forEach(function(e, i) {
  schedule.schedule.onward.journey.forEach(function(e2, i2) {
    if (e.flightNumber == e2.trips[0].FlightNumber) {
      e2.trips[0] = $.extend(e, e2.trips[0]);
    }
  });
});

工作示例:

var schedule = {
  "schedule": {
    "onward": {
      "journey": [{
        "trips": [{
          "origin": {
            "airportCode": "AMS"
          },
          "destination": {
            "airportCode": "BCN"
          },
          "FlightNumber": "KL1665"
        }]
      }, {
        "trips": [{
          "origin": {
            "airportCode": "AMS"
          },
          "destination": {
            "airportCode": "BCN"
          },
          "FlightNumber": "MF9343"
        }]
      }]
    }
  }
};

var flights = {
  "flights": [{
      "flightNumber": "KL1665",
      "price": 223,
      "available": 10
    }, {
      "flightNumber": "KL112",
      "price": 223,
      "available": 10
    }, {
      "flightNumber": " KL112",
      "price": 223,
      "available": 10
    }

  ]
};

flights.flights.forEach(function(e, i) {
  schedule.schedule.onward.journey.forEach(function(e2, i2) {
    if (e.flightNumber == e2.trips[0].FlightNumber) {
      e2.trips[0] = $.extend(e, e2.trips[0]);
    }
  });
});

console.log(schedule);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>