I have some nested Json in a file called data.json. I am using fetch
to read the file in and then would like to do some filtering based on if a user has a specific option selected in a dropdown on the website.
var jsonData = [{"type": "FeatureCollection",
"features": [
{"type": 'Feature', "properties": {"id": 1}, "geometry": {"type": "Point", "coordinates": [-80.71, 28.34]}},
{"type": 'Feature', "properties": {"id": 2}, "geometry": {"type": "Point", "coordinates": [-79.89, 28.45]}},
{"type": 'Feature', "properties": {"id": 2}, "geometry": {"type": "Point", "coordinates": [-60.79, 28.32]}}
]}
]
I would like to perform some filtering on this array of features based on the "properties": {"id": #}
field. E.g. if a user selects a value that matches that id, keep that in my result display data, else remove it.
I am trying to do something via a Promise like below. I'm new to JavaScript but the usage of .filter
in the below code is my attempt to get this to work.
Ideal solution I want to achieve:
I am displaying a map of data on the U.S. Map with points relative to some locations that belong to the id
field I mentioned. I would like the user to be able to click one of the IDs via a drop-down facility in Javascript, then via their selection, filter the JSON data to only features that belong to that Id. E.g. a traditional filter you'd use on data.
function filterIds(data) {
let idFilter= document.getElementById("id-filter");
let selection = idFilter.addEventListener('change', function(event) {
return this.value;
});
data.features.map((element) => {
// spread out our array of data and filter on specific property (namely, the id key)
return {...element, properties: element.filter((property) => property.id=== selection)};
});
async function getData(url) {
let response = await fetch(url);
let data = await response.json();
// console.log(data);
return data;
};
getData("../data/processed/data.json") // fetch raw data
.then(data => filterIds(data));