2

I'll try to explain.

I have a form with 7 inputs (Age, country, city,...) and in a JSON file i have many people. I need to search into that json file with all the criteria in the form. For example Spain&25years old.

I have the inputs data in an array, but i'm not able or don't know how to compare that criteria and retrieve info from JSON file.

Code below:

    <!-- 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 -->

The JSON file look like this:

{"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"
}

]}

The array from the form gives me back this:

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: ""} 

And I need to comare the form fields with some fields in the JSON, not all data. So i need to compare all those form fields with the JSON, and in case one is empty, compare the rest.

2 Answers2

1

You simply need to loop through the records in the json file, and check each record against your input record.

Within each iteration of the loop you need to do another loop over the input record fields, comparing them to the current record one property at a time.

If you are looking for an exact match, you can speed things up by continuing on to the next record as soon as one field does not match.

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
beeglebug
  • 3,522
  • 1
  • 23
  • 39
  • Thanks beeglebug, but i think this doesn't work for me. I need to compare some fields of the JSON not all, cuase i have extra data in that JSON file. I have updated my code to show the JSON estructure. – Diego Santamarta Nov 23 '12 at 17:48
  • I've updated data up so you can see what i want to achieve. Thanks in advance. Diego – Diego Santamarta Nov 27 '12 at 08:40
0

Use linq.js Here is the sample copypasted from 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();
Boris Gappov
  • 2,483
  • 18
  • 23