2

My data is this:

var manholeInfo = [{name: "manhole", date_key: "date"}]

I would like to make a table like this picture:

Desired output

But it comes out like this:

Actual output


Code:

var iwContent = document.createElement("div");
iwContent.className = 'infowindow';
iwContent.setAttribute('style', "width:160px;text-align:center;padding:5px");

var manholeInfo = [{
  name: "manhole",
  date_key: "2020-10-29"
}]

var table = document.createElement('table');

for (let element of manholeInfo) {
  let row = table.insertRow();
  for (let key in element) {
    let column = row.insertCell();
    column.innerHTML = element[key];
  }
}

iwContent.appendChild(table);
document.body.appendChild(iwContent);

0

2 Answers 2

3

Place the table.insertRow inside the inner for loop, and create separate cells for each key/value:

var iwContent = document.createElement("div");
iwContent.className = 'infowindow';
iwContent.setAttribute('style', "width:160px; text-align:center; padding:5px");

var manholeInfo = [{
  name: "manhole",
  date_key: "2020-10-29"
}]

var table = document.createElement('table');

for (let element of manholeInfo) {
  for (let key in element) {
    let row = table.insertRow();
    let columnKey = row.insertCell();
    let columnValue = row.insertCell();

    columnKey.innerHTML = key;
    columnValue.innerHTML = element[key];
  }
}

iwContent.appendChild(table);
document.body.appendChild(iwContent);

Sign up to request clarification or add additional context in comments.

Comments

1

var iwContent = document.createElement("div");
iwContent.className = 'infowindow';
iwContent.setAttribute('style', "width:250px; text-align:center; padding:5px");

var manholeInfo = [{
    name: "manhole",
    date_key: "2020-10-29"
}]

var table = document.createElement('table');
for (var i = 0; i < manholeInfo.length; i++) {

    var child = manholeInfo[i];

    Object.keys(child).forEach(function (k) {
        // console.log(k);
        var row = table.insertRow();
        var cell_1 = row.insertCell();
        var cell_2 = row.insertCell();
        cell_1.appendChild(document.createTextNode(k));
        cell_2.appendChild(document.createTextNode(child[k]));
    })
}

iwContent.appendChild(table);
document.body.appendChild(iwContent);
td {
    border: solid 1px #ddd;
    border-collapse: collapse;
    padding: 5px 6px;
    text-align: center;
    font-weight: bold;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.