[英]Join or lookup two JSON dataset
我有两个以下结构的JSON数据,这些数据是我使用getJSON jquery从服务器获取的。
countrylist = [
{ "Country": "United States", "Code": "us" },
{ "Country": "Belgium", "Code": "be" },
{ "Country": "Argentina", "Code": "ar" },
.
.
.
]
citylist = [
{ "City": "Abernant", "ContryCode": "us", "CityId"=1 },
{ "City": "Academy Park", "ContryCode": "be", "CityId"=2},
{ "City": "Abernathy", "ContryCode": "ar","CityId"=3 },
.
.
.
]
我需要在div中显示城市,国家/地区,如何从Citylist对象的countrylist中查找countrCode并将其完整的Country放入。 所以我可以展示
Abernant, United States
Academy Park, Belgium
Abernathy, Argentina
到目前为止我有这个代码
$.getJSON('../GetCountrylist', function (data) {
var countryList =data;
});
$.getJSON('../GetCitylist', function (data) {
//this is where i need to Join the data
//for each data dispaydata= data.City ',' + Country
});
您可以使用countrylist.Code
作为属性来转换countrylist
。 使这个国家变得微不足道。
var countries = {};
$.each(countrylist, function(i, country){
countries[ country.Code ] = country.Country;
});
现在,您可以遍历citylist
并从countries
地区获得countries
。
$.each(citylist, function(j, city){
console.log(city.City + "," + countries[ city.ContryCode ]);
});
var cityList = [];
var countryList = [];
// Assumption: You get countryList populated before calling this one
$.getJSON('../GetCitylist', function (data) {
cityList = data;
var outputString = '';
for(var i in cityList) { // these are each objects ?
// Assumption: You have no spaces in your property names
outputString += cityList[i].City + ',';
// You could also use cityList[i]['City'] if you expect spaces in your property
// names - same below - choose the accessor method that's most appropriate to
// your data
for(var j in countryList) { // these are also objects ?
if(countryList[j].Code === cityList[i].CountryCode) {
outputString += countryList[j].Country;
}
}
outputString += '<br />';
}
$('.selector').html(outputString);
});
这是使用$.extend
的可能解决方案:
var countrylist = [{ "Country": "United States", "Code": "us" }, { "Country": "Belgium", "Code": "be" }, {"Country": "Argentina", "Code": "ar" }],
citylist = [{ "City": "Abernant", "Code": "us", "CityId":1},{ "City": "Academy Park", "Code": "be", "CityId": 2},{ "City": "Abernathy", "Code": "ar","CityId":3 }],
newArray = [];
$.each(citylist, function(idx,val){
var code = val.Code;
$.each(countrylist,function(x,valu){
if(valu.Code === code){
newArray.push($.extend({},valu,val));
}
});
});
console.log(newArray);
您可以使用Alasql JavaScript库来实现。
这是一个主要运算符:
var data = alasql('SELECT city.City, country.Country FROM ? AS city \
JOIN ? AS country ON city.CountryCode = country.Code',[citylist, countrylist]);
在jsFiddle上尝试此示例 。
Alasql可以将JSON数据直接下载到SELECT语句:
alasql("SELECT city.City, country.Country \
FROM JSON('../GetCountrylist') AS city \
JOIN JSON('../GetCitylist') AS country \
ON city.CountryCode = country.Code",[], function(data){
// use data
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.