mapping in html js
Javascript Data map in get bootstrap table with forEach Method
If you want to use JavaScript to map data into a Bootstrap table, here's an example approach:
- Prepare your data: Use an array of objects to represent your table rows.
- Create the Bootstrap table: Write the HTML structure with appropriate headers.
- Map the data: Use JavaScript to populate the table dynamically.
Here's an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Table Example</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody id="table-body">
<!-- Data will be inserted here by JavaScript -->
</tbody>
</table>
</div>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js">
</script>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js)
// Sample dataconst data = [ { id: 1, name: "John Doe", age: 28, city: "New York" }, { id: 2, name: "Jane Smith", age: 34, city: "Los Angeles" }, { id: 3, name: "Sam Wilson", age: 23, city: "Chicago" }, { id: 3, name: "Ramesh", age: 23, city: "Chicago" }, { id: 3, name: "Suresh", age: 23, city: "Chicago" }, { id: 3, name: "Kishore", age: 23, city: "Chicago" }, { id: 3, name: "Sam Wilson", age: 23, city: "Chicago" }, ]; // Get the table body element const tableBody = document.getElementById("table-body"); // Map data into the table data.forEach((item, index) => { const row = document.createElement("tr"); row.innerHTML = ` <td>${index + 1}</td> <td>${item.name}</td> <td>${item.age}</td> <td>${item.city}</td> `; tableBody.appendChild(row); });
// Sample data
const data = [
{ id: 1, name: "John Doe", age: 28, city: "New York" },
{ id: 2, name: "Jane Smith", age: 34, city: "Los Angeles" },
{ id: 3, name: "Sam Wilson", age: 23, city: "Chicago" },
{ id: 3, name: "Ramesh", age: 23, city: "Chicago" },
{ id: 3, name: "Suresh", age: 23, city: "Chicago" },
{ id: 3, name: "Kishore", age: 23, city: "Chicago" },
{ id: 3, name: "Sam Wilson", age: 23, city: "Chicago" },
];
// Get the table body element
const tableBody = document.getElementById("table-body");
// Map data into the table
data.forEach((item, index) => {
const row = document.createElement("tr");
row.innerHTML = `
<td>${index + 1}</td>
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.city}</td>
`;
tableBody.appendChild(row);
});