thechoosenone thechoosenone - 2 months ago 8
Javascript Question

How to merge two objects with different structure in javascript

I Have two objects with different structure, trying to merge this two objects with matched data based on a key value, and make a new object with complete data from object1 and object2.

my Object1

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


object 2

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


i Would like to merge "price" and "available" to object which matches with "flightNumber" and create a new object with all data.

I have tried to use loadash and underscore but couldnt figure it. Help would be great, Thank in Advance.

Answer

2 simple forEach will do it:-

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]);
    }
  });
});

Working example:

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>

Comments