0

I have an array of objects with all values being different:

[
    {"val"::val,"xxx":"zzz","eee":"fff"},
    {"val":val},
    {val"::val,"xxx":"zzz","eee":"fff","val":val,"xxx":"zzz","eee":"fff"}
]

There are different values with different property names. I'm trying to dynamically display them in a html table.

The point would be to have a table without headers where the length of a row can be different from the previous one and where only specified values are displayed.

In the previous example the result would be a table with: 3 rows.

The first row having 3 cell
val | zzz | fff 

second row 1 cell
val |

Third row 6 cell
val | zzz | fff | val | zzz | fff

How can I generate such a table knowing that I wont know the key of any value and will need to display only the value and that without th. I also can't predict the length of the document.

2
  • What is the expected behavior when a row is not as long as the others? Are you expecting it to use rowspan to fill the remainder of the empty cells, or are you simply expecting the remainder of the row to be empty cells? I'm not sure what you want to accomplish. Commented Nov 10, 2016 at 2:28
  • Do values having the same key have to be displayed under the same column? Commented Nov 10, 2016 at 3:16

1 Answer 1

2

Object should not have duplicate property names. :: is not valid syntax. You can Array.prototype.forEach(), Object.keys() to append <tr> and <td> elements to <table> element.

var arr = [{
  "val": "val",
  "xxx": "zzz",
  "eee": "fff"
}, {
  "val": "val"
}, {
  "val": "val",
  "xxx": "zzz",
  "eee": "fff",
  "val1": "val",
  "xxx1": "zzz",
  "eee1": "fff"
}];

var table = document.querySelector("table");

arr.forEach(function(value, key) {
  var tr = table.insertRow();
  var keys = Object.keys(value);
  keys.forEach(function(prop, key) {
    var td = tr.insertCell();
    td.innerHTML = value[prop] + (key < keys.length - 1 ? " | " : "");
    tr.appendChild(td);
  });
});
<table>
  <tbody></tbody>
</table>

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

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.