1

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.push(product1);
ProductsArray.push(product2);
ProductsArray.push(product3);

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 |
+-----------------------------------+

<table>

    <tr>
        <th>Names</th>
        <td>Name1</>
        <td>Name2</>
        <td>Name3</>
    </tr>

    <tr>
        <th>Costs</th>
        <td>Cost1</>
        <td>Cost2</>
        <td>Cost3</>
    </tr>

    <tr>
        <th>Colors</th>
        <td>Color1</>
        <td>Color2</>
        <td>Color3</>
    </tr>

<table>

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++) {

    ProductsArray[i].Name
    ProductsArray[i].Cost
    ProductsArray[i].Color

}

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 <td> columns, then go through the values of each Cost and put them in a <td> etc...

3 Answers 3

2

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.

Demo: http://jsbin.com/gibez/1

function Product(name, cost, color) {
  this.name = 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 = props.map(function(prop) {
    return '<td>'+ data.map(pluck(prop)).join('</td><td>') +'</td>';
  });
  var rows = headers.map(function(head, i) {
    return '<tr><th>'+ head +'</th>'+ cells[i] +'<tr>';
  });
  return '<table>'+ rows.join('') +'</table>';
}

var tableHtml = table(
  products,
  ['name', 'cost', 'color'],
  ['Names', 'Costs', 'Colors']
);
Sign up to request clarification or add additional context in comments.

Comments

2

You can select the 3 trs ahead of time and use those as you iterate the array:

http://jsfiddle.net/QR7UZ/

<table>
    <tr>
        <th>Names</th>
    </tr>
    <tr>
        <th>Costs</th>
    </tr>
    <tr>
        <th>Colors</th>
    </tr>
</table>

var $trs = $('table tr');
var $nameTr = $trs.eq(0);
var $costTr = $trs.eq(1);
var $colorTr = $trs.eq(2);

$.each(ProductsArray, function(idx, item) {
    $('<td />').text(item.Name).appendTo($nameTr);
    $('<td />').text(item.Cost).appendTo($costTr);
    $('<td />').text(item.Color).appendTo($colorTr);
});

2 Comments

about 100 times better than my answer +1
@Jason P Good solution, simple and straight to the point, I never even thought about using eq, good thinking.
1

Hmm...you could add to three separate strings, that would each end up constituting a table row. Set up a skeleton table beforehand with the <tr> elements already in there, then run the script to fill each of them with <td> elements.

Maybe something like this (not sure how you're creating the elements, so I'll just use the jQuery .append() function).

HTML:

<table>
    <tr class="name">
        <th>Name</th>
    </tr>
    <tr class="cost">
        <th>Cost</th>
    </tr>
    <tr class="color">
        <th>Color</th>
    </tr>
</table>

JavaScript:

var nameHtml = "";
var costHtml = "";
var colorHtml = "";

// Building strings
for (var i = 0; i < ProductsArray.length; i++) {
    nameHtml += "<td>" + ProductsArray[i].Name + "</td>";
    costHtml += "<td>" + ProductsArray[i].Cost + "</td>";
    colorHtml += "<td>" + ProductsArray[i].Color + "</td>";
}

// Adding to rows
$(".name").append(nameHtml);
$(".cost").append(costHtml);
$(".color").append(colorHtml);

Here's a JSFiddle that demonstrates the example. There are plenty of ways to do this though, others have suggested some interesting ones. Main benefit here is that you can switch around table rows freely in the HTML without needing to change the JavaScript. Let me know if you have any questions. Hope this helps!

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.