检查JSON文件中的Array中的值

时间:2016-01-06 20:09:48

标签: javascript jquery json

我有一个JSON文件,我已经创建了一个jQuery函数来查找匹配的值,并在div中显示它们。我不太确定如何比较JSON文件中activities数组中的单个值。它似乎只返回整个数组。

如何检查JSON文件中的每个resort,看看JSON文件中activities数组中的某个值是否包含特定值,如scuba diving

JavaScript的:

var destination = $('option:selected', "#destination").attr('value');
var comfortLevel = $('option:selected', "#comfortLevel").attr('value');
var activities = $('option:selected', "#activities").attr('value');
var date = $('option:selected', "#date").attr('value');
var price = $('option:selected', "#price").attr('value');

$.getJSON('resort.json', function(data) {
    $.each(data.resorts, function(key, val) {
        if (destination == val.destination) {
            if (comfortLevel == val.comfortLevel || activties == val.activities || date == val.startDate || price > val.price) {
                $("#resortData").html("<img src= "+val.picture+" class='miniPic'> Destination: "+ val.destination + "<br>" + "Name: " + val.name + "<br>" +"Location: " 
                + val.location + "<br>" + "Comfort: " + val.comfortLevel + " Star <br>" + "Activities: " + val.activities + "<br>" + "Price: £" 
                + val.price + "<br>" + "Start Date: " + val.startDate + "<br>" + "End Date: " + val.endDate + "<br>" + "Description: " + val.short_description 
                + "<br><br>" + "<a href=':" + val.url +"'>Click HERE for more info</a>");
            }
        }
    });
});

resort.JSON:

{ 
    "resorts": [
        {
            "id":"resort1",
            "destination":"Carribean",
            "name":"Les Boucaniers",
            "location":"Martinique",
            "comfortLevel": "4",
            "activities":["water skiing", "tennis", "scuba diving", "kitesurf", "spa"],
            "price":1254,
            "startDate":"2016-01-01",
            "endDate":"2016-12-31",
            "short_description":"The resort of Les Boucaniers is located on the laid-back beach-covered south coast of the island, and is perfectly placed for Martinique holidays that are both relaxing and awe-inspiring.",
            "picture":"images/resort1pic1small.jpg",
            "long_description":"A divers' paradise in the Baie du Marin, a legendary spot.<br>Its bungalows are discreetly lodged in a tropical garden beside the white sand beach in superb Marin Bay. A magical site where you can enjoy a taste of everything, alone or with family or friends. Try water sports and the magnificent Club Med Spa*. You'll be enchanted by the exotic flavours of the local cuisine and the joyful spirit of the Caribbean.",
            "url":"resorts/resort1.html"
        },
        {
            "id":"resort2",
            "destination":"Indian Ocean",
            "name":"La Plantation d'Albion",
            "location":"Mauritius",
            "comfortLevel": "5",
            "activities":["kids club","golf", "scuba diving", "flying trapeze", "tennis", "sailing", "spa"],
            "price":2062,
            "startDate":"2016-01-01",
            "endDate":"2016-12-31",
            "short_description":"Beautifully located in one of the last remote creeks on the island, La Plantation d'Albion Club Med welcomes the most demanding of guests into a world of supreme refinement.",
            "picture":"images/resort2pic1small.jpg",
            "long_description":"In a remote beauty spot, savour the luxury of Mauritian lifestyle. <br> The idyllic natural setting is enhanced by the sublime decor designed by Marc Hertrich and Nicolas Adnet, and the Resort's top-end comfort is perfectly reflected in its beautifully spacious rooms. The exceptional CINQ MONDES Spa* and luxurious overflow pool add an ideally Zen touch.<br> The Resort is entirely devoted to fulfilling its guests' desires and offers discreet, personal service in its swimming areas, bars and 'Table Gourmet' restaurants.",
            "url":"resorts/resort2.html"
        }
]}

2 个答案:

答案 0 :(得分:1)

  

如何检查JSON文件中的每个求助文件,看看是否有其中一个   JSON文件中的activities数组中的值包含一个   具体价值如水肺潜水

在活动数组上使用indexOf()

请注意,这里有一个拼写错误(活动):if (comfortLevel == val.comfortLevel || activties == val.activities ...

答案 1 :(得分:0)

有点棘手,但有时RegExp有助于此类情况并节省大量代码:

var escape = /[.?*+^$[\]\\(){}|-]/g;
var destination = $('option:selected', "#destination").attr('value').replace(escape, "//$&");
var comfortLevel = $('option:selected', "#comfortLevel").attr('value');
var activities = $('option:selected', "#activities").attr('value').replace(escape, "//$&");
var date = $('option:selected', "#date").attr('value').replace(escape, "//$&");
var price = $('option:selected', "#price").attr('value');

$.get('resort.json', function(data) {

    var json = JSON.parse( data.match(new RegExp('(\{[^\{\}]*?"destination"\s*\:\s*"' + destination + '"[^\}]*(?:"comfortLevel"\s*\:\s*"' + comfortLevel + '"|"activities"\s*\:\s*\[[^\]]*"' + activities + '"[^\]]*\]|"date"\s*\:\s*"' + date + '"|"price"\s*\:\s*(?:' + "[0-" + price.split("").join("]?[0-") + "]?" + '))[^\{\}]*?\})'))[0] );

    $("#resortData").html("<img src= "+json.picture+" class='miniPic'> Destination: "+ json.destination + "<br>" + "Name: " + json.name + "<br>" +"Location: " 
        + json.location + "<br>" + "Comfort: " + json.comfortLevel + " Star <br>" + "Activities: " + json.activities + "<br>" + "Price: £" 
        + json.price + "<br>" + "Start Date: " + json.startDate + "<br>" + "End Date: " + json.endDate + "<br>" + "Description: " + json.short_description 
        + "<br><br>" + "<a href=':" + json.url +"'>Click HERE for more info</a>");

});

要测试RegExp中是否包含某项活动的Array的特定部分是:

'"activities"\s*\:\s*\[[^\]]*"' + activities + '"[^\]]*\]'