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

How can I access a specific item in JSON object based on a value?

本文关键字:对象 JSON 何根 访问      更新时间:2023-09-26

我在从一组数据中获取我想要的信息时遇到了一点麻烦(见下文)。基本上,我需要得到每种不同类型燃料的价格。一开始我假设数据中的每一项都有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"
}]

如果我理解正确的话,关键问题是您需要将数据从索引转换为键=>值。

如果你有一个这样的函数:

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