Filter JSON data using $getJSON

Viewed 558

I have the following code, which is loading in the full JSON file.

$.getJSON("data/Data1.json", function (data) {
  currentStatus.addData(data);
  map.addLayer(currentStatusLayer);
});

What I am trying to do is filter the JSON file, but am struggling to get only the filtered value from the JSON data record.

What I am trying to get is the record which has 'Status: Watch'.

Here is my code below:

$.getJSON("data/Data1.json", function (data) {
  currentStatus = data.features.filter(function(feature) {
    return feature.status === 'Watch';
});
  currentStatus.addData(data);
  map.addLayer(currentStatusLayer);

});

Trimmed down JSON data file:

[
        {
            "type": "Feature",
            "id": 0,
            "status": "watch",
            "properties": {
                "NAME": "Watch Test"              
            }
           
        },

        {
            "type": "Feature",
            "id": 1,
            "status": "act",
            "properties": {
                "NAME": "Act Test"        
            }          
        }
    ]

Thank you

2 Answers

filter will remove item(s) based on your criteria from the features array.

I believe you would like to use find in order to find item in your array of features:


currentStatus = data.features.find(function(feature) {
  return feature.status.toLowerCase() === 'watch';
}

Please keep in mind, that find method returns the value of the first element in the provided array.

Pro tip: convert your status property with toLowerCase() method to make sure that you are comparing case agnostic strings.

You could always use filter like this:

$.getJSON("data/Data1.json", function (data) {
  ///set your variable - you did this part right:
  var items = data;
  // now apply your filter:
items = data.filter(function(obj) {
  // return the filtered value
  return obj.status ==="watch";
});

// verify in your console:
console.log(items);

// continue with your project ;)
  currentStatus.addData(items);
  map.addLayer(currentStatusLayer);
});

This should work for your filtering.

Related