I would like to format the content of my popup so that null
values are completely removed. At this point, my popup is filled with the features.properties
array. There are 20 elements in properties
, and depending on the queried feature, many of those values will be null
.
var feature = features[0];
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(feature.geometry.coordinates)
.setHTML('<div><b>' + feature.properties.city + '</div></b>' + '<div>'
+ feature.properties.course1 + '</div>' + '<div>'+
feature.properties.course2 + '<div>' + feature.properties.course3 + '</div>')
.addTo(map);
At this point, an example popup with some null
values looks like this:
My aim is to eliminate null
values and not to display them in the popup.
So far I've tried the JSON.stringify
option instead of listing each element in separate <div>
element.
function replacer(key, value) {
// Filtering out properties
if (value === "null" || value === null) {
return undefined;
}
return value;
}
JSON.stringify(feature.properties, replacer, "\t").replace(/\"/g, "").replace(/,/g, "")
This produces the desired result but then formatting is the problem.
The JSON object does not display well in a popup even when encasing it in <pre>
tags, which produces:
I would like to know if there is a solution to format my popup so that it looks like the first image - but excludes null values. How can one do this is html
by listing all of the property elements (course1
, course2
, course3
, etc...) without producing a bunch of empty <div>
s?