Merge by Grep / Map 2 JSON objects ~ Andrew Pougher
Merge by Grep / Map JQuery, 2 JSON objects ~ Andrew Pougher
by Andrew Pougher
HTML
<div id="merge1"></div>
<hr>
<pre id="merge2"></pre>
JavaScript
var travel_data =
[{"country":"France","resort":"Chamonix","snowdepth":"5"},
{"country":"Switzerland","resort":"Verbier","snowdepth":"13"},
{"country":"Italy","resort":"Tourin","snowdepth":"11"}]
var hotel_data =
[{"country":"Switzerland","hotelCount":"1234"},
{"country":"France","hotelCount":"975"},
{"country":"Italy","hotelCount":"834"}]
var combined = $.map(travel_data, function(obj, i) {
return $.extend({}, obj, $.grep(hotel_data, function(stock_obj) {
return obj.country === stock_obj.country
})[0]);
});
$('#merge1').append("<pre>" +
JSON.stringify(combined, null, 4) +
"</pre>");
$('#merge2').append("{'travelData':\n");
$('#merge2').append( JSON.stringify(combined, null, 4) +"}");