我正在尝试使用ammap绘制线条而且我无法为起点和终点生成坐标数组。我必须使用具有case_study作为密钥的json数组,如下所示
var data = {
"countries_involved": [
{"c_id": 6, "country": "India", "longitude": "21", "latitude": "78.0000", "involvement": 3, "case_study": 4},
{"c_id": 7, "country": "Canada", "longitude": "62", "latitude": "105.3809", "involvement": 3, "case_study": 4},
{"c_id": 8, "country": "Comoros", "longitude": "12", "latitude": "44.2333", "involvement": 1, "case_study": 5},
{"c_id": 9, "country": "Madagascar", "longitude": "20", "latitude": "47.0000", "involvement": 1, "case_study": 5},
{"c_id": 10, "country": "Mauritius", "longitude": "20", "latitude": "57.5000", "involvement": 1, "case_study": 5}
],
"country_details": [
{"name": "Kenya", "longitude": "-1", "latitude": "36.8000", "case_study": 4},
{"name": "Kenya", "longitude": "-1", "latitude": "36.8000", "case_study": 5}
]
};
我正在使用jquery过滤器以下列格式返回数据
{longitudes: [country_details.longitude,countries_involved.longitude], latitudes: [country_details.latitude,countries_involved.latitude],}
这是我在for循环中的函数
for (var i = 0; i < data.country_details.length; i++)
{
var obj = {
id: data.country_details[i]['name'].replace(/\s+/g, ''),
color: "#000000",
svgPath: targetSVG,
title: data.country_details[i]['country'],
latitude: data.country_details[i]['longitude'],
longitude: data.country_details[i]['latitude'],
scale: 1.5,
zoomLevel: 2.74,
lines: data.countries_involved.filter(function(involved) {
return involved.case_study === data.country_details[i].case_study
}).map(function(item) {
return {latitudes: [data.country_details[i].latitude, item.latitude], longitudes: [data.country_details[i].longitude, item.longitude]}
})
};
}
但是,我只得到一个仅包含起点但不是终点的数组,这意味着item.latitude
和item.longitude
没有评估。有人可以帮帮忙吗?
答案 0 :(得分:2)
在这段代码中:
data.countries_involved.filter(function(involved){
return involved.case_study === data.country_details[i].case_study
}).map(function(item){
return {
latitudes: [data.country_details[i].latitude, item.latitude],
longitudes: [data.country_details[i].longitude, item.longitude]
};
});
未定义变量'i'。
我相信在内置javascript数组'map'和'filter'函数的情况下,您正在迭代的集合中的索引将作为 second 参数传递。因此,将'i'声明为这两行中的第二个参数:
data.countries_involved.filter(function(involved, i){
// and:
}).map(function(item, i){
编辑: Array.prototype.map和Array.prototype.filter并非在所有浏览器中都可用。要使用jQuery map和filter,请执行以下操作:
$($.grep(data.countries_involved, function(involved){
return involved.case_study === data.country_details[i].case_study
})).map(function(idx, item){
return {
latitudes: [data.country_details[i].latitude, item.latitude],
longitudes: [data.country_details[i].longitude, item.longitude]
};
}).get()