Eric Bergman Eric Bergman - 7 days ago 4x
HTML Question

Create vertical column table based on Array of Objects

Let's say I have a Javascript Array of Product Objects

function Product() {
this.Name = "";
this.Cost = "";
this.Color = "";

var ProductsArray = [];

var product1 = new Product();
product1.Name = "Name1";
product1.Cost = "Cost1";
product1.Color = "Color1";

var product2 = new Product();
product2.Name = "Name2";
product2.Cost = "Cost2";
product2.Color = "Color2";

var product3 = new Product();
product3.Name = "Name3";
product3.Cost = "Cost3";
product3.Color = "Color3";


ProductsArray now has the following

product1: [Name1, Cost1, Color1],
product2: [Name2, Cost2, Color2],
product3: [Name3, Cost3, Color3]

How do I loop through this Array of Objects so that I'm able to create table dynamically through jQuery which as the following format:

It's sort of like a table whose columns are horizontal

| Names | Name 1 | Name 2 | Name 3 |
| Costs | Cost 1 | Cost 2 | Cost 3 |
| Colors | Color1 | Color2 | Color3 |






I guess the problem I'm having is since I loop through the Array in this fashion:

for (var i = 0; i < ProductsArray.length; i++) {



I can only go through one object at time so I need a way to go through the values of each section each iteration, for example I need to go through the values of each Name and put them in
columns, then go through the values of each Cost and put them in a


I would suggest a slightly different approach. First I'd pass the arguments in the constructor, then I'd create the products array with instances and a function to make the HTML for your table.

You can use this with any collection, not only instances, but regular objects as well, just pass an array of objects, the properties to show, and the headers for each of those properties.


function Product(name, cost, color) { = name;
  this.cost = cost;
  this.color = color;

var products = [
  new Product('name1', 'cost1', 'color1'),
  new Product('name2', 'cost2', 'color2'),
  new Product('name3', 'cost3', 'color3')

function pluck(prop) {
  return function(x) {
    return x[prop];

function table(data, props, headers) {
  var cells = {
    return '<td>'+'</td><td>') +'</td>';
  var rows =, i) {
    return '<tr><th>'+ head +'</th>'+ cells[i] +'<tr>';
  return '<table>'+ rows.join('') +'</table>';

var tableHtml = table(
  ['name', 'cost', 'color'],
  ['Names', 'Costs', 'Colors']