根据最小和最大价格过滤JSON数据

时间:2022-09-27 09:00:46

I'm not sure how to filter my JSON data according to price (specified in my JSON data - price) I have two drop down lists, one for min price and the other for max price. The data from my json needs to be within the range of my two drop down lists and if it does, some data needs to be outputted in my html page from my JSON i.e ID, Price, Type, description, etc. I'm a beginner and learning.

我不确定如何根据价格过滤我的JSON数据(在我的JSON数据中指定 - 价格)我有两个下拉列表,一个用于最低价格,另一个用于最高价格。来自我的json的数据需要在我的两个下拉列表的范围内,如果是这样,一些数据需要从我的JSON页面输出我的JSON,即ID,价格,类型,描述等。我是一个初学者和学习。

This is my JSON data

这是我的JSON数据

{
    "Properties": [
        {
            "id": "prop1",
            "type": "House",
            "bedrooms": 3,
            "price": 650000,
            "tenure": "Freehold",
            "description": "Attractive three bedroom semi-detached family home situated within 0.5 miles of Petts Wood station with fast trains to London and within easy walking distance of local shops, schools, bus routes and National Trust woodland. The property comprises; two receptions, fitted 18'9 x 10'1 kitchen/breakfast room and conservatory. The property also benefits from having a utility room and cloakroom. To the first floor there are three bedrooms and a family bathroom with separate WC. Additional features include double glazing, gas central heating and a well presented interior...",
            "location": "Petts Wood Road, Petts Wood, Orpington",
            "picture": "images/prop1pic1small.jpg",
            "url": "properties/prop1.html",
            "added": {
                "month": "January",
                "day": 12,
                "year": 2014
            }
        },
        {
            "id": "prop2",
            "type": "Flat",
            "bedrooms": 2,
            "price": 299995,
            "tenure": "Freehold",
            "description": "Presented in excellent decorative order throughout is this two double bedroom, two bathroom, garden flat. <br>The modern fitted kitchen is open plan to the living room which boasts solid wooden floors and includes integrated appliances including a dishwasher & a washing machine. This large open plan benefits from bi folding doors onto a secluded private courtyard garden. Both bedrooms are double sized, and the family bathroom boasts a matching three piece suite a shower attachment over the bath. There is also a separate wet room. There are walnut doors throughout and wiring for Sky TV/aerial points in the living room/kitchen and both bedrooms.<br>This apartment being only five years old, is still under a 10 year building guarantee...",
            "location": "Crofton Road Orpington BR6",
            "picture": "images/prop2pic1small.jpg",
            "url": "properties/prop2.html",
            "added": {
                "month": "September",
                "day": 14,
                "year": 2014
            }
        },
        {
            "id": "prop3",
            "type": "House",
            "bedrooms": 4,
            "price": 950000,
            "tenure": "Freehold",
            "description": "Addison Townends are delighted to offer this outstanding semi detached house of over 2500 square feet located in this prestigious location within 500 yards of Southgate Underground Station and within excellent primary and secondary school catchments. The property offers four double bedrooms, two bathrooms, two receptions, kitchen/breakfast room and downstairs cloakroom. Externally the property boasts two driveways of over 60' each both with gated access, double garage, studio with en-suite shower room and approximately 85' South West facing rear garden. The property is offered chain free and internal viewing comes highly recommended.",
            "location": "High Street London",
            "picture": "images/prop3.jpg",
            "url": "properties/prop3.html",
            "added": {
                "month": "November",
                "day": 19,
                "year": 2014
            }
        },
        {
            "id": "prop4",
            "type": "House",
            "bedrooms": 5,
            "price": 825000,
            "tenure": "Freehold",
            "description": "A charming five bedroom semi detached family home boasting many original features, conveniently located on the High Street in Southgate. This characterful property offers 2122 sq ft.",
            "location": "High Street Southgate",
            "picture": "images/prop4.jpg",
            "url": "properties/prop4.html",
            "added": {
                "month": "October",
                "day": 23,
                "year": 2014
            }
        },
        {
            "id": "prop5",
            "type": "Flat",
            "bedrooms": 5,
            "price": 64999950,
            "tenure": "Freehold",
            "description": "Apartment C.08.1 is an exceptional apartment stretching across the entire floor plate of pavilion C and as such boasts magnificent views of both Knightsbridge and Hyde Park. The interior design of Apartment C.08.1 responds both to its unique size as well as its extraordinary location. The apartment is divided into two wings; the five bedrooms can be found in the city wing whilst all the living and entertaining spaces are in the park wing.",
            "location": "Knightsbridge  London  SW1X 7LJ",
            "picture": "images/prop5.jpg",
            "url": "properties/prop5.html",
            "added": {
                "month": "March",
                "day": 15,
                "year": 2014
            }
        },
        {
            "id": "prop6",
            "type": "House",
            "bedrooms": 3,
            "price": 200000,
            "tenure": "Freehold",
            "description": "Fitted kitchen with a range of wall and base units, cupboard housing boiler, sink and drainer ,rolled edge worksurfaces, gas and electric cooker point, plumbing for washing machine and space for fridge freezer. Feature gas fire with marble surround,serving hatch and dual double glazed window to front and rear aspect, two radiators. UPVC door to front, under stairs storage, stairs to first floor, radiator and door to lounge/dining area.",
            "location": "Bandley Rise Stevenage SG2",
            "picture": "images/prop6.jpg",
            "url": "properties/prop6.html",
            "added": {
                "month": "August",
                "day": 4,
                "year": 2014
            }
        },
        {
            "id": "prop7",
            "type": "Flat",
            "bedrooms": 2,
            "price": 200000,
            "tenure": "Freehold",
            "description": "Offered with no onward chain located in the centre of Romford within 0.3 miles of Romford Main Line Station is this two bedroom apartment. Benefitting from en-suite to the master bedroom, as well as a 23ft lounge/kitchen with bi-folding doors opening onto the balcony. The property also has the addition of a family bathroom and own secure parking space. EPC C.",
            "location": "Rubicon Court South Street Romford RM1",
            "picture": "images/prop7.jpg",
            "url": "properties/prop7.html",
            "added": {
                "month": "July",
                "day": 23,
                "year": 2014
            }
        }
    ]
}

And this is my HTML with Java Script

这是我用Java Script编写的HTML

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
    <script>
        $(document).ready(function() {
            $("#search").on("click", function() {
                $.getJSON('data.json', function(data) {
                    var minPrice = $("minPrice").val();
                    var maxPrice = $("maxPrice").val();
                    var output = "<ul>";
                    for (var l in data.Properties) {
                        if ((data.Properties[l].price >= minPrice) && (data.Properties[l].price <= maxPrice)) {

                            output += "<li>" + data.Properties[l].id + "</li>";
                            output += '<img src="' + data.Properties[l].picture + '" />';
                            output += "</ul>";
                            document.getElementById("placeholder").innerHTML = output;
                        }
                    }
                });
            });
        });
    </script>
    <form>
        <select id="minPrice" name="minPrice">
            <option value="100000">100000</option>
            <option value="150000">£150,000</option>
            <option value="200000">£200,000</option>
            <option value="250000">£250,000</option>
        </select>
        <select id="maxPrice" name="maxPrice">
            <option value="100000">£100,000</option>
            <option value="150000">£150,000</option>
            <option value="200000">£200,000</option>
            <option value="6000000">25000000</option>
        </select>
    </form>
    <button id="search">Search Staff</button>
</body>
</html>

Any help is appreciated, thanks

任何帮助表示赞赏,谢谢

3 个解决方案

#1


1  

Can you correct this and try (added hash before ID):

你可以纠正这个并尝试(在ID之前添加哈希):

var minPrice = $("#minPrice").val();
var maxPrice = $("#maxPrice").val();

#2


0  

After taking @sudip-pal's advise you'll have to loop through the data yourself. jQuery pales in comparison to other tools sadly. There are several options, ES5 (The modern browser) has built-in methods for managing loops, For older browsers Underscore or Lo-Dash do wonders for these kinds of operations.

在接受@ sudip-pal的建议后,你必须自己循环访问数据。令人遗憾的是,jQuery与其他工具相比显得相形见绌。有几种选择,ES5(现代浏览器)具有用于管理循环的内置方法,对于较旧的浏览器,Underscore或Lo-Dash为这些类型的操作创造了奇迹。

Since this question was JS / jQuery only I'll show two methods (ES5 and jQuery only):

由于这个问题只是JS / jQuery,我将展示两种方法(仅限ES5和jQuery):

ECMAScript 5

function filterByPriceRange(objects, min, max) {
  return objects.reduce(function(memo, object) {
    if (min <= object.price < max) {
      memo.push(object);
    }
    return memo;
  }, []);
}

jQuery (old browsers)

function filterByPriceRange(objects, min, max) {
  var result = [];
  $.each(objects, function(index, object) {
    if (min <= object.price < max) {
      result.push(object);
    }
  });
  return result;
}

Underscore / Lo-Dash

By comparison here is the same with a utility library:

相比之下,实用程序库与此相同:

function filterByPriceRange(objects, min, max) {
  return _.filter(objects, function(object) {
    return (min <= object.price < max);
  });
}

#3


0  

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
    <script>


        $(document).ready(function() {
            $("#search").on("click", function() {
                $.getJSON('data.json', function(data) {
                    var minPrice = $("#minPrice").val();
                    var maxPrice = $("#maxPrice").val();
                    var output = "<ul>";

                    for (var l in data.Properties) {  //alert('price==>'+data.Properties[l].price);
                        if ((parseInt(data.Properties[l].price) >= parseInt(minPrice))  && (parseInt(data.Properties[l].price) <= parseInt(maxPrice))) {

                            output += "<li>" + data.Properties[l].id + "</li>";
                            output += '<img src="' + data.Properties[l].picture + '" />';
                            output += "</ul>";
                            //alert(data.Properties[l].id);

                        }
                    }
                    $("#placeholder").html(output);
                });
            });
        });
    </script>
    <form>
        <select id="minPrice" name="minPrice">
            <option value="1000000">100000</option>
            <option value="1500000">£150,000</option>
            <option value="2000000">£200,000</option>
            <option value="2500000">£250,000</option>
        </select>
        <select id="maxPrice" name="maxPrice">
            <option value="100000">£100,000</option>
            <option value="150000">£150,000</option>
            <option value="200000">£200,000</option>
            <option value="6000000">25000000</option>
        </select>
    </form>
    <button id="search">Search Staff</button>
    <div id="placeholder"></div>
</body>
</html>

#1


1  

Can you correct this and try (added hash before ID):

你可以纠正这个并尝试(在ID之前添加哈希):

var minPrice = $("#minPrice").val();
var maxPrice = $("#maxPrice").val();

#2


0  

After taking @sudip-pal's advise you'll have to loop through the data yourself. jQuery pales in comparison to other tools sadly. There are several options, ES5 (The modern browser) has built-in methods for managing loops, For older browsers Underscore or Lo-Dash do wonders for these kinds of operations.

在接受@ sudip-pal的建议后,你必须自己循环访问数据。令人遗憾的是,jQuery与其他工具相比显得相形见绌。有几种选择,ES5(现代浏览器)具有用于管理循环的内置方法,对于较旧的浏览器,Underscore或Lo-Dash为这些类型的操作创造了奇迹。

Since this question was JS / jQuery only I'll show two methods (ES5 and jQuery only):

由于这个问题只是JS / jQuery,我将展示两种方法(仅限ES5和jQuery):

ECMAScript 5

function filterByPriceRange(objects, min, max) {
  return objects.reduce(function(memo, object) {
    if (min <= object.price < max) {
      memo.push(object);
    }
    return memo;
  }, []);
}

jQuery (old browsers)

function filterByPriceRange(objects, min, max) {
  var result = [];
  $.each(objects, function(index, object) {
    if (min <= object.price < max) {
      result.push(object);
    }
  });
  return result;
}

Underscore / Lo-Dash

By comparison here is the same with a utility library:

相比之下,实用程序库与此相同:

function filterByPriceRange(objects, min, max) {
  return _.filter(objects, function(object) {
    return (min <= object.price < max);
  });
}

#3


0  

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
    <script>


        $(document).ready(function() {
            $("#search").on("click", function() {
                $.getJSON('data.json', function(data) {
                    var minPrice = $("#minPrice").val();
                    var maxPrice = $("#maxPrice").val();
                    var output = "<ul>";

                    for (var l in data.Properties) {  //alert('price==>'+data.Properties[l].price);
                        if ((parseInt(data.Properties[l].price) >= parseInt(minPrice))  && (parseInt(data.Properties[l].price) <= parseInt(maxPrice))) {

                            output += "<li>" + data.Properties[l].id + "</li>";
                            output += '<img src="' + data.Properties[l].picture + '" />';
                            output += "</ul>";
                            //alert(data.Properties[l].id);

                        }
                    }
                    $("#placeholder").html(output);
                });
            });
        });
    </script>
    <form>
        <select id="minPrice" name="minPrice">
            <option value="1000000">100000</option>
            <option value="1500000">£150,000</option>
            <option value="2000000">£200,000</option>
            <option value="2500000">£250,000</option>
        </select>
        <select id="maxPrice" name="maxPrice">
            <option value="100000">£100,000</option>
            <option value="150000">£150,000</option>
            <option value="200000">£200,000</option>
            <option value="6000000">25000000</option>
        </select>
    </form>
    <button id="search">Search Staff</button>
    <div id="placeholder"></div>
</body>
</html>