从html弹出窗口中删除空值

时间:2017-01-12 11:15:58

标签: javascript html popup mapbox

我想格式化弹出窗口的内容,以便完全删除null个值。此时,我的弹出窗口中充满了features.properties数组。 properties中有20个元素,根据查询的功能,其中许多值为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);

此时,带有一些null值的示例弹出窗口如下所示:

enter image description here

我的目标是消除null值,而不是在弹出窗口中显示它们。

到目前为止,我已经尝试了JSON.stringify选项,而不是将每个元素列在单独的<div>元素中。

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, "") 

这会产生所需的结果,但格式化就是问题。

enter image description here

即使将<pre>标记包含在html标记中,JSON对象也无法在弹出窗口中很好地显示,这会生成:

enter image description here

我想知道是否有解决方案来格式化我的弹出窗口,使其看起来像第一个图像 - 但不包括空值。如何通过列出所有属性元素course1course2course3等来<div>来执行此操作... 没有产生一堆空的POST /oauth/token

2 个答案:

答案 0 :(得分:1)

这是使用经典Javascript的一种方式:

&#13;
&#13;
var features = {
  properties: {
    city: "Salzburg",
    course1: "DCLead",
    course2: "null",
    course3: null,
    field_1: "Hello"
  }
};

function htmlFromProps(props, exclude) {
  var html = "";
  var i = 0;
  for (p in props) {
    if (props[p] && props[p] != "null" && exclude.indexOf(p) === -1) {
      html += "<div>" + (i === 0 ? "<strong>" : "");
      html += props[p];
      html += (i++ === 0 ? "</strong>" : "") + "</div>\n";
    }
  }
  return html;
}

popup.innerHTML = htmlFromProps(features.properties, ["field_1"]);
&#13;
#popup {
  width: 80%
}
&#13;
<textarea id="popup"></textarea>
&#13;
&#13;
&#13;

通过调用.setHTML(htmlFromProps(features.properties, []))来使用它,其中第二个参数是您要排除的字段数组。

答案 1 :(得分:0)

您可以尝试过滤您的属性,请参阅以下示例:

&#13;
&#13;
var feature = {
  properties: {
    city: 'Salzburg',
    course1: 'test',
    course3: 'test3'
  }
};

var html = Object
  .keys(feature.properties)
  .map(key => feature.properties[key])
  .filter(value => value)
  .map((value, i) => i === 0
      ? `<div><strong>${value}</strong></div>`
      : `<div>${value}</div>`
      )

console.log(html);
&#13;
&#13;
&#13;

关键部分是.filter(value => value),其中filter确保数组中只保留truthy(非空)值。