我有一个json文件,其结构如下:
{
"gasStationID":"441",
"gasStationLat":"39.6337420",
"gasStationLong":"22.4324412",
"fuelCompID":"6",
"fuelCompNormalName":"AVIN",
"ddID":"42010100",
"municipalityID":"42010000",
"countyID":"42000000",
"phone1":null,
"username":"user1",
"fuelTypeID":"1",
"fuelPrice":"1.379"
},
{
"gasStationID":"441",
"gasStationLat":"39.6337420",
"gasStationLong":"22.4324412",
"fuelCompID":"6",
"fuelCompNormalName":"AVIN",
"ddID":"42010100",
"municipalityID":"42010000",
"countyID":"42000000",
"phone1":null,
"username":"user1",
"fuelTypeID":"1",
"fuelPrice":"1.478"
}
所以,我的问题是如何使用fuelPrice
检索fuelTypeID=1
?
我的JavaScript文件是:
for (i = 0; i < obj.length; i++) {
var _gasStationCompName = obj[i].fuelCompNormalName;
var priceID = obj[i].fuelTypeID;
switch (fuelId) {
case '1':
case priceID == 1:
price = obj[i].fuelPrice;
break;
case '2':
case priceID == 2:
price = obj[i].fuelPrice;
break;
default:
price = "0";
}
我的问题是price = obj[i].fuelPrice
只显示fuelPrice
fuelType=2
。如何在switch语句中过滤结果?
在此之前,我正在解析JSON文件。此外,您可以看到我有case: '1'
。那是因为我的HTML文件中有这样的东西:
<div>
<select onChange="getData(this.value);">
<option value="1">Gas</option>
<option value="2">Diesel</option>
</select>
</div>
答案 0 :(得分:0)
变量和对象键区分大小写(A!= a);
for (i = 0; i < obj.length; i++) {
var _gasStationCompName = obj[i].fuelCompNormalName;
var priceID = obj[i].fuelTypeID; // fuelTypeId => fuelTypeID
switch (priceID) { fuelTypeId // => priceID
case '1':
case priceID == 1:
price = obj[i].fuelPrice;
break;
case '2':
case priceID == 2:
price = obj[i].fuelPrice;
break;
default:
price = "0";
}
}
答案 1 :(得分:0)
我假设JSON是一个数组。让我们调用该数组gasStations
。
// Given a collection of stations and a fuel type, find the price
function findPrice(collection, fuelType) {
// Find the station with the target fuel type
var targetStation = collection.filter(function (station) {
return station.fuelTypeID === fuelType;
})[0];
// If there was a match, return that station's price
if (targetStation) {
return targetStation.fuelPrice;
}
// Default to "0" if there was no match
return "0";
}
// usage
var price = findPrice(gasStations, "1");
注意:如果您有一个集合,其中多个工作站具有目标燃料类型,此功能将返回具有该燃料类型的第一个加油站的价格。
答案 2 :(得分:0)
我设法找到了解决方案。这是一个正确的开关语句,就像一个魅力:
var priceID = obj[i].fuelTypeID;
switch (fuelTypeID) {
case '1':
if (priceID == 1) {
price = obj[i].fuelPrice;
}
break;
case '2':
if (priceID == 2) {
price = obj[i].fuelPrice;
}
break;
default:
price = 0;
}