New StackOverflow Question: Removing nulls from html popup

2 views
Skip to first unread message

stacko...@mg.bodar.com

unread,
Mar 7, 2017, 5:10:48 AM3/7/17
to total...@googlegroups.com

Removing nulls from html popup

Asked by the_darkside on 2017-01-12T11:15:57Z

Reply on StackOverflow

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:

enter image description here

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.

enter image description here

The JSON object does not display well in a popup even when encasing it in <pre> tags, which produces:

enter image description here

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?

Reply on StackOverflow
Reply all
Reply to author
Forward
0 new messages