Lasagna Cat
Lasagna Cat

Reputation: 397

JavaScript array filtering and mapping produces comma in between array entries?

The following code allows me to append entries from a JSON array onto a webpage and inside table elements:

//define a function that will fetch status and set icon URL
function setServerProcessesServer1761() {
  var url = "Server1761.json";
  var $svc = $("#Server1761-processes"); //get a reference to your <div>

  $.getJSON(url, function(data) {
    document.getElementById(
      "Server1761-processes"
    ).innerHTML = data.processes
      .filter(s => s.Name.value.includes("company_name"))
      .map(
        s =>
          `<table><tr><td>${s.Name.value}</td> <td>${
            s.Status
          }</td></tr></table>`
      );
    $("#Server1761-processes").html(function(_, html) {
      return html.replace(/runn1ng/g, "<img src='smallgreen.png' />");
    });
    $("#Server1761-processes").html(function(_, html) {
      return html.replace(/fai1ed/g, "<img src='smallred.png' />");
    });
  }); // you will have to concatenate the entire services request line on line 130
}

//special jQuery syntax to run when document is ready (like onload but better)
$(function() {
  setServerProcessesServer1761();
});

What ends up happening is after each table row, there is a comma , that gets plugged in:

enter image description here

I thought I had unintentionally scripted it inside the code, but when I tried CTRL+F I did not find any commas to be in place.

I thought about it some more, and my next guess is that it is appending the JSON entries as listed in the array, whereas commas exist in the JSON arrays.

My question is, how can I remove the commas from being listed from the JSON array and allow my table row entries to look more of a comprehensive table with no breaks or commas such as this:

enter image description here

Upvotes: 0

Views: 378

Answers (1)

nem035
nem035

Reputation: 35481

When you set innerHTML of an element to an array

elem.innerHTML = [1, 2, 3]

that array gets converted to a string behind the scenes and then rendered to the DOM.

Stringifying an array, by default, joins all of its elements with a comma in between.

console.log(
  [1, 2, 3].toString() === [1, 2, 3].join(',')
)

You can overwrite this by manually joining on something else, for example a new line:

console.log(
  [1, 2, 3].join('\n')
)

Upvotes: 4

Related Questions