简体   繁体   中英

Dynamically Creating / Implementing Data in A Table with a 2D Array in Javascript/Html

The goal I am trying to achieve is to dynamically create a table with data based off of the info from a 2D array. I've seen examples of table creation with 1D arrays, but I can't seem to wrap around creating it with 2D. Furthermore, once this table is created, I need to be able to manipulate it, for example deleting a row with insignificant information etc. I like to use a nested for loop for this. This needs to be created with Javascript / Html. The table for example :

|item   | price | description|

|chicken | $20  | yummy |

And the array [0][0] is chicken, [0][1] is $20, [0][2] is yummy. Any help / leads are appreciated!.

Do a nested for loop:

let myArray = [['chicken', '$20', 'yummy']];
let myTable = '<table>';

for(let row = 0; row < myArray.length; row++){

    myTable += '<tr>'; // Create a row
    for(let col = 0; col < myArray[row].length; col++){
        myTable += `<td>${myArray[row][col]}</td>`; // Create a cell with the data
    }
    myTable += '</tr>'; // Close the row

}

myTable += '</table>'; // Finally close the table

This should create you a table with the array values.

Below uses strictly dom manipulation to build your table, creating the necessary elements (ie HTML, TBODY, THEAD, TR, TD, TH) and building the structure over the course of a loop.

The performance of doing so can be improved, but this depends on how big your table (and the content of it) is. Doing string concatenation and then binding to the dom in most cases will be faster, except for very large tables. There are also other disadvantages to using string interpolation, such as escaping certain characters (dom manipulation handles this for you).

Only you can determine how big/small your table is and make the judgement.

DOM Manipulation

 'use strict'; let arr = [ ['item', 'price', 'description'], ['chicken', '$20', 'yummy'] ], doc = document; // Create DOM elements let table = doc.createElement('table'), thead = doc.createElement('thead'), tbody = doc.createElement('tbody'); // Create cells and rows arr.forEach((data, i) => { let tr = doc.createElement('tr'); let container = tbody; let cell_type = 'td'; if (i == 0) { container = thead; cell_type = 'th'; } // Create and attach cells to row data.forEach(text => { let td = doc.createElement(cell_type); td.appendChild(doc.createTextNode(text)); tr.appendChild(td); }); // Attach TR to THEAD/TBODY container.appendChild(tr); }); // Attach THEAD/TBODY to TABLE table.appendChild(thead); table.appendChild(tbody); // Append Table to Document doc.querySelector('body').appendChild(table); 
 table { border: 1px solid #999; border-collapse: collapse; margin-top: 2rem; } td, th { border: 1px solid #ccc; border-collapse: collapse; padding: .25rem; } th { text-transform: capitalize; } 

String Concatenation

 'use strict'; let arr = [ ['item', 'price', 'description'], ['chicken', '$20', 'yummy'] ]; // Build Rows let rows = arr.map((data, i) => { let type = i == 0 ? 'th' : 'td'; let cells = data.map(text => `<${type}>${text}</${type}>`) return `<tr>${cells.join('')}</tr>`; }); // Build Table let table = `<table> <thead>${rows.shift()}</thead> <tbody>${rows.join('')}</tbody> </table>`; // Append Table to Document document.querySelector('body').innerHTML += table; 
 table { border: 1px solid #999; border-collapse: collapse; margin-top: 2rem; } td, th { border: 1px solid #ccc; border-collapse: collapse; padding: .25rem; } th { text-transform: capitalize; } 

Do it dynamically with Vanilla and ES6

 const food = [{ Item: "chicken", Price: "$20", Description: "buck,buck,,,,, buck,,, buckAHHHH yumm" }, { Item: "Beef", Price: "$20", Description: "Moo yumm" }, { Item: "Dog", Price: "$20", Description: "woof-woof yumm" }, { Item: "Cat", Price: "$20", Description: "meow-meow yumm" }]; function tableCreate(items) { let lables = items.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []); items.unshift(lables); let body = document.body, tbl = document.createElement('table'); tbl.style.width = '100px'; tbl.style.border = '1px solid black'; for (let [i, index] of items.entries()) { let tr = tbl.insertRow(); for (let j in items[i]) { let td = tr.insertCell(); td.appendChild(document.createTextNode(items[i][j])); td.style.border = '1px solid black'; } } body.appendChild(tbl); tbl.rows[0].style.fontWeight = 'bold'; } tableCreate(food); 

And you can modify it like so

 const food = [{ Item: "chicken", Price: "$20", Description: "buck,buck,,,,, buck,,, buckAHHHH yumm" }, { Item: "Beef", Price: "$20", Description: "Moo yumm" }, { Item: "Dog", Price: "$20", Description: "woof-woof yumm" }, { Item: "Cat", Price: "$20", Description: "meow-meow yumm" }]; function tableCreate(items) { let lables = items.reduce((s, o) => [...new Set([...s, ...Object.keys(o)])], []); items.unshift(lables); let body = document.body, tbl = document.createElement('table'); tbl.style.width = '100px'; tbl.style.border = '1px solid black'; for (let [i, index] of items.entries()) { let tr = tbl.insertRow(); for (let j in items[i]) { let td = tr.insertCell(); td.appendChild(document.createTextNode(items[i][j])); td.style.border = '1px solid black'; } } body.appendChild(tbl); tbl.rows[0].style.fontWeight = 'bold'; } const modify = { remove(from, val) { for (let [i, product] of from.entries()) { if (product.Item === val) { console.log(i) from.splice(i, 1); console.log(from) } } }, removeOnLengthsLargerThan(from, val) { for (let [i, product] of from.entries()) { if (product.Description) { if (product.Description.length > val) { from.splice(i, 1); } } } }, shorten(from, val) { for (let [i, product] of from.entries()) { if (product.Description) { if (product.Description.length > val) { product.Description = product.Description.substr(0, val); } } } } } modify.shorten(food, 10); console.log('shorten',food); modify.remove(food, 'chicken'); console.log('remove',food); modify.removeOnLengthsLargerThan(food, 10) console.log('removeOnLengthsLargerThan',food); tableCreate(food); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM