我很难从一组数据中获取想要的信息(请参阅下文)。本质上,我需要获取每种不同类型燃料的燃料价格。最初,我是在假设数据中的每一项都包含所有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"
                }
                ]
        }
        ]
};

最佳答案

由于尚未提及,因此另一种方法是使用JSON路径。

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


将返回:

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

09-19 01:34