如何根据值访问JSON对象中的特定项?

时间:2015-07-15 19:26:14

标签: javascript json

我在从一组数据中获取所需信息时遇到了一些麻烦(见下文)。基本上,我需要为每种不同类型的燃料获得燃料价格。最初我假设数据中的每个项目都有4种类型的燃料,所以如果我想要柴油价格,我可以说data.locations[i].fuelTypes[3].price。但是,我们假设一家商店没有优质燃气 - 那么柴油将位于fuelTypes[2]

有没有办法根据描述在fuelTypes数组中查找该项目?现在我唯一能想到的就是遍历fuelTypes数组中的所有内容并说出

if (data.locations[i].fuelTypes[j].description == 'Diesel') {
    gasPrice = data.locations[i].fuelTypes[j].price;
}

但这似乎对大量记录效率低下。

这是我正在使用的数据的简化版本。

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"
                }
                ]
        }
        ]
};

2 个答案:

答案 0 :(得分:0)

另一种方法,因为没有提到过使用JSON路径。

$..fuelTypes[?(@.description=='Diesel')]

会回来:

[{
    "description": "Diesel",
    "price": "4.00",
    "currency": "USD"
},
{
    "description": "Diesel",
    "price": "4.00",
    "currency": "USD"
}]

答案 1 :(得分:0)

如果我理解正确,那么基本问题是您需要将数据从索引转换为key => value。

如果你有这样的功能:

function toKeyValue(fuelTypesArray) {
    ob = {};
    for (var i = 0; i < fuelTypesArray.length; i++) {
        ob[fuelTypesArray[i].description] = {
            price: fuelTypesArray[i].price,
            currency: fuelTypesArray[i].currency
        };
    }
    return ob;
}

然后不是像下面那样不可能访问Diesel:

data.locations[i].fuelTypes[3].price

您可以使用

toKeyValue(data.locations[i].fuelTypes)["Diesel"].price