2

我会尽力解释。

我有一个包含 7 个输入(年龄、国家、城市……)的表单,在 JSON 文件中我有很多人。我需要使用表单中的所有条件搜索该 json 文件。例如西班牙&25 岁。

我在数组中有输入数据,但我无法或不知道如何比较该标准并从 JSON 文件中检索信息。

下面的代码:

    <!-- Google Maps -->
<script src="assets/js/jquery.ui.map.full.min.js"></script>
<script src="assets/js/jquery.ui.map.extensions.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
  $(function(){
    $('#mapa').gmap({'callback': function() {
      var self = this;
      parsejson = function(arrayvalues){
        $.getJSON( 'mapa.json', function(data) { 
          $.each(arrayvalues, function(x, val) {
            if (val.value !== "") {
              console.log(val.value);
              $.each( data.markers, function(i, marker) {
                console.log('marker ' + marker);
                // PROBLEM IS HERE, DON'T KNOW HOW TO SOLVE



              });
            };
          });

          // Draw markers in map

          // $.each( data.markers, function(i, marker) {
          //   self.addMarker({ 
          //     'position': new google.maps.LatLng(marker.latitude, marker.longitude), 
          //     'bounds': false
          //   }).click(function() {
          //     self.openInfoWindow({'content': marker.content }, this);
          //   });
          // });
        });

      };

      self.getCurrentPosition(function(position, status) {
        if ( status === 'OK' ) {
          var clientPosition = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          self.addMarker({'position': clientPosition, 'bounds': false});
          self.option('center', clientPosition);
          self.option('zoom', 12);
          self.addShape('Circle', { 
            'strokeColor': "#008595",
            'strokeOpacity': 0.8,
            'strokeWeight': 2,
            'fillColor': "#008595",
            'fillOpacity': 0.35,
            'center': clientPosition,
            'radius': 500,
            'clickable': false
          });
        }
        else {
          console.log("else");
          var clientPosition = new google.maps.LatLng(40.463667, -3.74922);
          self.option('center', clientPosition);
          self.option('zoom', 4);
        }
      });
    }});
  });

  // Search form actions
  $('#searcher-form').submit(function(e) {
    e.preventDefault();
    var $inputs = $(this).serializeArray();

    parsejson($inputs);
  });
</script>
<!-- End of Google Maps -->

JSON 文件如下所示:

{"markers":[
{
    "fromcountry":"Spain",
    "fromcity":"San Cristóbal de la Laguna",
    "livecountry":"Spain",
    "livecity":"San Cristóbal de la Laguna",
    "age":25,
    "profession":"Diseñador"
    "title":"La Laguna",
    "latitude":28.469294910391532,
    "longitude":-16.329975128173828,
    "content":"Mooola"
},
{
    "fromcountry":"Spain",
    "fromcity":"Madrid",
    "livecountry":"Spain",
    "livecity":"Santa Crus de Tenerife",
    "age":30,
    "profession":"Programador"
    "title":"Los Majuelos",
    "latitude":28.44038127509586,
    "longitude":-16.311674416065216,
    "content":"Mooola"
}

]}

表单中的数组给了我这个:

Object {name: "regsearchcountry", value: "whatever"}
Object {name: "regsearchcity", value: "whatever"}
Object {name: "regsearchlivecountry", value: ""}
Object {name: "regsearchlivecity", value: "whatever"}
Object {name: "regsearchagefrom", value: ""}
Object {name: "regsearchageto", value: "whatever"}
Object {name: "regsearchprofession", value: ""} 

我需要将表单字段与 JSON 中的某些字段进行比较,而不是所有数据。所以我需要将所有这些表单字段与 JSON 进行比较,如果一个为空,则比较其余的。

4

2 回答 2

1

您只需要遍历 json 文件中的记录,并根据您的输入记录检查每条记录。

在循环的每次迭代中,您需要对输入记录字段进行另一个循环,一次将它们与当前记录比较一个属性。

如果您正在寻找完全匹配的内容,您可以通过在一个字段不匹配时立即继续下一条记录来加快速度。

var records = [
    { name : 'bob', age : 22 },
    { name : 'john', age : 32 }
    /* lots of other records */
];

var input = {
    name : 'john',
    age : 32
};


var compare, match, result;

    // loop through all the records
for(var i = 0, len = records.length; i < len; i++) {

    compare = records[i];

    match = true;

            // loop through each property (name, age etc)
    for(prop in input) {

                    // as soon as something is wrong, break out and try the next one
        if(input[prop] !== compare[prop]) { 

            match = false;
            break;

        }

    }

            // if we got through without anything being wrong, we found the result!
    if(match) {

        result = compare;
        break;

    }

}

// result should be set to a matching result
于 2012-11-23T15:23:07.733 回答
0

使用 linq.js 这是从http://linqjs.codeplex.com/复制粘贴的示例

var jsonArray = [
    { "user": { "id": 100, "screen_name": "d_linq" }, "text": "to objects" },
    { "user": { "id": 130, "screen_name": "c_bill" }, "text": "g" },
    { "user": { "id": 155, "screen_name": "b_mskk" }, "text": "kabushiki kaisha" },
    { "user": { "id": 301, "screen_name": "a_xbox" }, "text": "halo reach" }
]
// ["b_mskk:kabushiki kaisha", "c_bill:g", "d_linq:to objects"]
var queryResult = Enumerable.From(jsonArray)
    .Where(function (x) { return x.user.id < 200 })
    .OrderBy(function (x) { return x.user.screen_name })
    .Select(function (x) { return x.user.screen_name + ':' + x.text })
    .ToArray();
// shortcut! string lambda selector
var queryResult2 = Enumerable.From(jsonArray)
    .Where("$.user.id < 200")
    .OrderBy("$.user.screen_name")
    .Select("$.user.screen_name + ':' + $.text")
    .ToArray();
于 2012-11-23T15:33:15.170 回答