2

I've been tasked with populating an HTML table using javascript arrays, but I'm having a lot of trouble understanding how to get my arrays to populate an actual HTML table. I have to create a table that has 5 menu item images, 5 menu item descriptions, and their 5 prices. I have my arrays provided below, but don't know what functions I need to perform to get the arrays to populate the HTML table. What do you recommend I do to get them populating in an HTML table?

Also, as per the assignment, I must use a numeric array to store the prices and a string array to store the image files.

I think I have to perform some kind of 'for' loop, but I'm not sure.

Thanks for all of your help, and please let me know how I can refine this question.

Thanks,

//my arrays

var item = ["Chicken soup", "Chicken tacos", "Chicken quesadilla", "Chicken burrito", "Chicken enchilada"];

var itemDescription = ["Delicious creamy chicken soup", "Homemade tacos", "Cheesy chicken quesadillas", "Hearty stuffed chicken burrito", "World famous chicken enchilada"];

var itemPrice = [14.99, 17.99, 15.75, 22.95, 12.55];

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = 'chickensoup.jpg';

imgArray[1] = new Image();
imgArray[1].src = 'chickentaco.jpg';

imgArray[2] = new Image();
imgArray[2].src = 'chickenque.jpg';

imgArray[3] = new Image();
imgArray[3].src = 'chickenburrito.jpg';

imgArray[4] = new Image();
imgArray[4].src = 'chickenenchilada.jpg';
1

4 Answers 4

1

For starters I would recommend merging the arrays into one, to avoid any errors regarding indices.

The standard html format is of the type:

<table>
    <thead>
        <tr>
            <th>name</th>
            <th>description</th>
            <th>price</th>
            <th>imageSrc</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Chicken soup</td>
            <td>Delicious creamy chicken soup</td>
            <td>14.99</td>
            <td><img src="chickensoup.jpg" alt="chickensoup.jpg"></td>
        </tr>
    </tbody>
</table>

So you need one loop to print all the headers. You need one loop to create a different row for each item. You need one last loop inside the row loop to add each cell (food property) to the row.

var items = [{
  name: "Chicken soup",
  description: "Delicious creamy chicken soup",
  price: 14.99,
  imageSrc: "chickensoup.jpg"
}, {
  name: "Chicken tacos",
  description: "Homemade tacos",
  price: 17.99,
  imageSrc: "chickentaco.jpg"
}, {
  name: "Chicken quesadilla",
  description: "Cheesy chicken quesadillas",
  price: 15.75,
  imageSrc: "chickenque.jpg"
}, {
  name: "Chicken burrito",
  description: "Hearty stuffed chicken burrito",
  price: 22.95,
  imageSrc: "chickenburrito.jpg"
}, {
  name: "Chicken enchilada",
  description: "World famous chicken enchilada",
  price: 12.55,
  imageSrc: "chickenenchilada.jpg"
}];

var propertyList = ["name", "description", "price", "imageSrc"];

var table = document.createElement("table");
var tableHeader = document.createElement("thead");
var tableHeaderRow = document.createElement("tr");
var tableBody = document.createElement("tbody");

table.setAttribute("border", "1");

document.body.appendChild(table);
table.appendChild(tableHeader);
tableHeader.appendChild(tableHeaderRow);
table.appendChild(tableBody);

propertyList.forEach(function(key) {
  var headerCell = document.createElement("th");
  tableHeaderRow.appendChild(headerCell);
  headerCell.textContent = key;
});


items.forEach(function(foodItem) {
  var foodRow = document.createElement("tr");
  tableBody.appendChild(foodRow);
  propertyList.forEach(function(propertyName) {
    var foodProperty = document.createElement("td");
    foodRow.appendChild(foodProperty);
    if (propertyName === "imageSrc") {
      var image = document.createElement("img");
      foodProperty.appendChild(image);
      image.src = foodItem[propertyName];
      image.alt = foodItem[propertyName];
    } else {
      foodProperty.textContent = foodItem[propertyName];
    }
  });
});

If you cannot merge the arrays then you can use this instead.

var item = ["Chicken soup", "Chicken tacos", "Chicken quesadilla", "Chicken burrito", "Chicken enchilada"];

var itemDescription = ["Delicious creamy chicken soup", "Homemade tacos", "Cheesy chicken quesadillas", "Hearty stuffed chicken burrito", "World famous chicken enchilada"];

var itemPrice = [14.99, 17.99, 15.75, 22.95, 12.55];

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = 'chickensoup.jpg';

imgArray[1] = new Image();
imgArray[1].src = 'chickentaco.jpg';

imgArray[2] = new Image();
imgArray[2].src = 'chickenque.jpg';

imgArray[3] = new Image();
imgArray[3].src = 'chickenburrito.jpg';

imgArray[4] = new Image();
imgArray[4].src = 'chickenenchilada.jpg';

var foodList = {
  name: item,
  description: itemDescription,
  price: itemPrice,
  imageSrc: imgArray
};

var propertyList = ["name", "description", "price", "imageSrc"];

var table = document.createElement("table");
var tableHeader = document.createElement("thead");
var tableHeaderRow = document.createElement("tr");
var tableBody = document.createElement("tbody");

table.setAttribute("border", "1");

document.body.appendChild(table);
table.appendChild(tableHeader);
tableHeader.appendChild(tableHeaderRow);
table.appendChild(tableBody);

propertyList.forEach(function(key) {
  var headerCell = document.createElement("th");
  tableHeaderRow.appendChild(headerCell);
  headerCell.textContent = key;
});

for (var index = 0; index < item.length; index++) {

  var foodRow = document.createElement("tr");
  tableBody.appendChild(foodRow);
  propertyList.forEach(function(propertyName) {
    var foodProperty = document.createElement("td");
    foodRow.appendChild(foodProperty);
    if (propertyName === "imageSrc") {
      foodProperty.appendChild(foodList[propertyName][index]);
    } else {
      foodProperty.textContent = foodList[propertyName][index];
    }
  });
}

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

3 Comments

Hello nick zoum, your code worked perfectly. I put it into my .js file and it showed up exactly how it was supposed to. Unfortunately, and this is my fault because I did not clarify, I'm tasked with using numeric arrays for the prices string arrays for the image files, so I cannot string all of the arrays into one. Does this make sense? Do you have another recommendation? Thanks for all your help.
@ImCanaan I added a second example in the answer
@ImCanaan I'm glad I could help. Please let me know if you need any further explanation regarding the code.
1

Try this:

let itemObject = [];

itemObject.push({
    item: 'Chicken soup',
    description: 'Delicious creamy chicken soup',
    price: 14.99,
    image: 'chickensoup.jpg'
});
itemObject.push({
    item: 'Chicken tacos',
    description: 'Chicken taco',
    price: 17.99,
    image: 'chickentaco.jpg'
});
itemObject.push({
    item: 'Chicken quesadilla',
    description: 'Chicken quesadilla',
    price: 15.75,
    image: 'chickenque.jpg'
});
itemObject.push({
    item: 'Chicken burrito',
    description: 'Chicken burrito',
    price: 22.95,
    image: 'chickenburrito.jpg'
});
itemObject.push({
    item: 'Chicken enchilada',
    description: 'Chicken enchilada',
    price: 12.55,
    image: 'chickenenchilada.jpg'
});


let tbody = document.getElementById('tbody');

for (let rows of itemObject) {
    let tr = document.createElement('TR');
    let td, tdText;
    for (let value of Object.values(rows)) {
        td = document.createElement("TD");
        td.appendChild(document.createTextNode(value));
        tr.appendChild(td);
    }
    tbody.appendChild(tr);
};
<table>
   <thead>
      <tr>
         <td>Item</td>
         <td>Description</td>
         <td>Price</td>
         <td>Image</td>
      </tr>
   </thead>
   <tbody id="tbody">
   </tbody>
</table>

5 Comments

The Object.keys part is redundant. You can just use forEach right away
Hello @Nerdvoso, I'm not sure whether the code you provided would work not because I used the code provided by nickzoum and it resolvled what I was working on. Thank you for taking the time to help me out with this.
@ImCanaan Quiet, I wanted to give my own version to solve the problem. Maybe it could interest someone else.
@nickzoum I have modified, thanks for the constructive signaling
@Nerdvoso You are still using in instead of of. Are you doing this for ES5 compatibility?
0

See this fiddle link https://jsfiddle.net/j5mnto3g/2/

Create a table in Html

<table border="1">
  <thead>
    <tr><th>Item Image</th><th>Item Name</th><th>Description</th><th>Price</th></tr>
  </thead>
  <tbody id="tbl-body"> </tbody>
</table>

and add row with in table by a simple for loop

var item = ["Chicken soup", "Chicken tacos", "Chicken quesadilla", "Chicken burrito", 
            "Chicken enchilada"];

var itemDescription = ["Delicious creamy chicken soup", "Homemade tacos", "Cheesy chicken quesadillas", "Hearty stuffed chicken burrito", "World famous chicken enchilada"];

var itemPrice = [14.99, 17.99, 15.75, 22.95, 12.55];

var imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = 'chickensoup.jpg';

imgArray[1] = new Image();
imgArray[1].src = 'chickentaco.jpg';

imgArray[2] = new Image();
imgArray[2].src = 'chickenque.jpg';

imgArray[3] = new Image();
imgArray[3].src = 'chickenburrito.jpg';

imgArray[4] = new Image();
imgArray[4].src = 'chickenenchilada.jpg';
var rows = '';
for(i = 0; i < item.length; i++){
    rows += '<tr><td><img src="'+imgArray[i]+'" width="20" height="20"></td><td>'+item[i]+'</td><td>'+itemDescription[i]+'</td><td>'+itemPrice[i]+'</td></tr>';
}
document.getElementById('tbl-body').innerHTML = rows;

Use correct image path and size

1 Comment

Hello @Avi I'm not sure why, but this did not resiolve it. nickzoum provided an example above that did do the trick. Thank you for your help. I appreciate you taking the time to help out.
-1

i wont show the whole code, but this is the best way to do this logically

//JS
let array = ["item 1", "item2"];

//start a string (of html)
let htmlDisplayed = "<div id='htmlString'><ul>";

//loop each array item as a list item
for (let i=0; i< array.length; i++) {
  htmlDisplayed = htmlDisplayed.concat(`<li>${array[i]}</li>`);
}

//close your html tags off
htmlDisplayed = htmlDisplayed.concat("</ul></div>");

//display it
document.getElementById("yourElement").innerHTML = htmlDisplayed;

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.