I'm having a bit of trouble getting the information I want out of a set of data (see below). Essentially, I need to get the fuel price for each different type of fuel. Originally I was working off the assumption that each item in the data had all 4 types of fuel, so if I wanted the diesel price, I could just say data.locations[i].fuelTypes[3].price
. However, let's say a store doesn't have Premium gas - then diesel would be located at fuelTypes[2]
.
Is there a way to look up the item in the fuelTypes array based on its description? Right now the only thing I can think of would be to iterate over everything in the fuelTypes array and say
if (data.locations[i].fuelTypes[j].description == 'Diesel') {
gasPrice = data.locations[i].fuelTypes[j].price;
}
But this seems like it would be inefficient over a large number of records.
Here's a simplified version of the data I'm working with.
var data = {
"locations": [
{
"name": "Store 1",
"fuelTypes": [
{
"description": "Unleaded",
"price": "1.00",
"currency": "USD"
},
{
"description": "Plus",
"price": "2.00",
"currency": "USD"
},
{
"description": "Premium",
"price": "3.00",
"currency": "USD"
},
{
"description": "Diesel",
"price": "4.00",
"currency": "USD"
}
]
},
{
"name": "Store 2",
"fuelTypes": [
{
"description": "Unleaded",
"price": "1.00",
"currency": "USD"
},
{
"description": "Plus",
"price": "2.00",
"currency": "USD"
},
{
"description": "Premium",
"price": "3.00",
"currency": "USD"
},
{
"description": "Diesel",
"price": "4.00",
"currency": "USD"
}
]
}
]
};