Adding data rows dynamically from a json object using javascript? - javascript

I have a json file in my website project, like this:
[
{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
]
Here it is the sample data, It has 4 columns but i don't know that my json data which i will get, will have how many number of columns. I am trying to create a dynamic html table from this json data. This is the code i have write now:
<script>
$(document).ready(function () {
var jsonitems = [];
$.getJSON("json.json", function (data) {
var totalColumns = Object.keys(data[0]).length;
var columnNames = [];
columnNames = Object.keys(data[0]);
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < totalColumns; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnNames[i];
row.appendChild(headerCell);
}
above code is working, I am facing problem when i try to insert data rows, below is the code for that which is not working:
//Add the data rows.
//for (var i = 1; i < data.length; i++) {
// row = table.insertRow(-1);
// for (var j = 0; j < totalColumns; j++) {
// var cell = row.insertCell(-1);
// cell.innerHTML = customers[i][j];
// }
//}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
});
});
</script>
Please help me with that.
Thanks

The way you are accessing the cell data is wrong. For example, to access id of first object, you've to do data[0]["id"], instead your code tries to do data[0][0]. Working example of your code:
var data = [{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
];
var totalColumns = Object.keys(data[0]).length;
var columnNames = [];
columnNames = Object.keys(data[0]);
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < totalColumns; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnNames[i];
row.appendChild(headerCell);
}
// Add the data rows.
for (var i = 0; i < data.length; i++) {
row = table.insertRow(-1);
columnNames.forEach(function(columnName) {
var cell = row.insertCell(-1);
cell.innerHTML = data[i][columnName];
});
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
<div id="dvTable"></div>

Based on what I can interpret, you can just do this. Access each object inside the array, then use the keys to map your values.
But what you've written as your example code and your provided data seems different.
let data = [
{
"id": "1",
"name": "ramesh",
"phone": "12345",
"salary": "50000"
},
{
"id": "2",
"name": "suresh",
"phone": "123456",
"salary": "60000"
}
];
var table = document.getElementById("table");
for (let item of data) {
row = table.insertRow(-1);
for (let key in item) {
var cell = row.insertCell(-1);
cell.innerHTML = item[key];
}
}
<table id="table">
</table>

Related

how to add button in javascript since the data that import in the html table is from JSON file

I am trying to add edit and delete button inside the column but the HTML table was created from JSON file and it is using for loop to print out the content. I don't know how to add extra button inside the column (green zone).
The button that plan to add will be replace in the 'undefined' col.
JSON code:
[
{
"userId":"ravjy",
"jobTitleName":"Developer",
"firstName":"Ran",
"lastName":"Vijay",
"preferredFullName":"Ran Vijay",
"employeeCode":"H9",
"region":"DL",
"phoneNumber":"34567689",
"emailAddress":"ranvijay.k.ran#gmail.com"
},
{
"userId":"mrvjy",
"jobTitleName":"Developer",
"firstName":"Murli",
"lastName":"Vijay",
"preferredFullName":"Murli Vijay",
"employeeCode":"A2","region":"MU",
"phoneNumber":"6543565",
"emailAddress":"murli#vijay.com"
}
]
<script>
fetch('employees.json')
.then(function (response) {
// The JSON data will arrive here
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
// If an error occured, you will catch it here
});
function appendData(data) {
//Extract Value for HTML HEADER.
var col=[];
for (var i = 0; i<data.length;i++){
for (var key in data[i]){
if (col.indexOf(key) === -1){
col.push(key);
}
}
}
//Add edit and delete header
col.push("Edit","Delete");
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("myData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
[1]: https://i.stack.imgur.com/YpoDi.png
[2]: https://i.stack.imgur.com/pu7SB.png
Solution
Javascript map will help to get that working
const data = [
{
userId: "ravjy",
jobTitleName: "Developer",
firstName: "Ran",
lastName: "Vijay",
preferredFullName: "Ran Vijay",
employeeCode: "H9",
region: "DL",
phoneNumber: "34567689",
emailAddress: "ranvijay.k.ran#gmail.com",
},
{
userId: "mrvjy",
jobTitleName: "Developer",
firstName: "Murli",
lastName: "Vijay",
preferredFullName: "Murli Vijay",
employeeCode: "A2",
region: "MU",
phoneNumber: "6543565",
emailAddress: "murli#vijay.com",
},
];
function test(type, id) {
alert(type + " " + id);
}
function appendData(data) {
//Extract Value for HTML HEADER.
data = data.map((item) => {
item.Edit_Delete = `<Button type="button" onclick="test('Edit', '${item.userId}')">${item.userId}</Button>
<Button type="button" onclick="test('Delete', '${item.userId}')">${item.userId}</Button>`;
return item;
});
const col = [];
for (let i = 0; i < data.length; i++) {
for (let key in data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
//Add edit and delete header
// col.push("Edit","Delete");
// CREATE DYNAMIC TABLE.
const table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
let tr = table.insertRow(-1); // TABLE ROW.
for (let i = 0; i < col.length; i++) {
const th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (let i = 0; i < data.length; i++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
const tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
const divContainer = document.getElementById("myData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
appendData(data);
<!DOCTYPE html>
<html>
<body>
<div id ="myData"></div>
</body>
</html>

How can I convert this json data to html table with javascript?

I want to create an HTML table using json data. The json data will change over time. When convert this json data to an HTML table, the table looks like this with consistent. It means the alignment of values and the width of the table. How can I convert the json data into an HTML table?
[
{
"1": [{
"Time": "01:35 AM",
"Location": "dhaka bangladesh",
"BUS Detail": {
"air_Logo": "logo goes here",
"air_Name": "Airbus"
},
"busNo": "AK119",
"arrTime": "05:40 AM",
"arrival Loc": "barisal"
}]
}
]`// Extract value from table header.
let col = [];
for (let i = 0; i < myBooks.length; i++) {
for (let key in myBooks[i]) {
if (col.indexOf(key) == -1) {
col.push(key);
}
}
}
// Create a table.
const table = document.createElement("table");
// Create table header row using the extracted headers above.
let tr = table.insertRow(-1); // table row.
for (let i = 0; i < col.length; i++) {
let th = document.createElement("th"); // table header.
th.innerHTML = col[i];
tr.appendChild(th);
}
// add json data to the table as rows.
for (let i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (let j = 0; j < col.length; j++) {
const tabcel = tr.insertCell(-1);
if (typeof myBooks[i][col[j]] === 'object') {
tabcel.setAttribute('rowspan','2');
tabcel.innerHTML = `<table><td>${myBooks[i][col[j]].air_Name}</td> <td> ${myBooks[i][col[j]].air_Logo}</td> </table>`;
} else {
tabcel.innerHTML = myBooks[i][col[j]];
}
}
// for (let j = 0; j < col.length; j++) {
// let tabCell = tr.insertCell(-1);
// tabCell.innerHTML = myBooks[i][col[j]];
// }
}
// Now, add the newly created table with json data, to a container.
const divShowData = document.getElementById('showData');
divShowData.innerHTML = "";
divShowData.appendChild(table);`
Since your object is not flat, you cannot truly render it all to table. You have to make a decision about the nested objects. Below I am simply using json.stringify to show those objects in a table cell. You should of course handle this according to your needs.
const data = [
{
"1": [
{
Time: "01:35 AM",
Location: "dhaka bangladesh",
"BUS Detail": {
air_Logo: "logo goes here",
air_Name: "Airbus"
},
busNo: "AK119",
arrTime: "05:40 AM",
"arrival Loc": "barisal"
}
]
}
];
const base = data[0]["1"];
const table = document.createElement("table");
const thead = table.createTHead();
const tbody = document.createElement("tbody");
table.append(tbody)
const headRow = thead.insertRow();
const headers = Object.keys(base[0]).forEach((head) => {
let cell = headRow.insertCell();
cell.textContent = head;
});
base.forEach((obj) => {
const row = tbody.insertRow();
const vals = Object.values(obj);
vals.forEach((v) => {
const cell = row.insertCell();
if (typeof(v) !== 'string') {
return cell.textContent = JSON.stringify(v);
}
cell.textContent = v
});
});
document.body.append(table)

How do I display only details of Linda using JSON

i would like to display only details of Linda using JSON. However, I am clueless on how to do it. Need some advice, thanks!
The output should show the updated table with only "Linda" instead of my current output.
Actual question:
Using JSON, modify the mobile of Linda to 88885555, and display only the details of Linda.
My employees object is supposed to be from .json file but i couldnt find the format to insert into this post. Hence, i combined it into my .js file.
var employees = [
{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
},
{
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
},
{
"Name": "Patrick",
"Email": "patrick#json.com"
},
{
"Name": "Isabella",
"Mobile": 99552222
}
];
employees[1].Mobile = 88885555;
function buildHtmlTable() {
var columns = addAllColumnHeaders(employees);
for (var i = 0; i < employees.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = employees[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#employeeTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(employees) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < employees.length; i++) {
var rowHash = employees[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#employeeTable").append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable()">
<table id="employeeTable" border="1"></table>
</body>
You can create a function that accepts an "employee name", .not() and .is() to match any <td> elements within the <tr> where .textContent is equal to the argument passed to the function, chain .hide() to set the display of the matched elements to "none".
To display all <tr> elements you can use $("#employeeTable tr").show().
Substituted using jQuery(function(){}) for onload attribute event handler at <body> element.
var employees = [{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
},
{
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
},
{
"Name": "Patrick",
"Email": "patrick#json.com"
},
{
"Name": "Isabella",
"Mobile": 99552222
}
];
employees[1].Mobile = 88885555;
function buildHtmlTable() {
var columns = addAllColumnHeaders(employees);
for (var i = 0; i < employees.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = employees[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#employeeTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(employees) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < employees.length; i++) {
var rowHash = employees[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#employeeTable").append(headerTr$);
return columnSet;
}
<!DOCTYPE html>
<html>
<head>
<title>Task 1</title>
<!-- using of jquery, calling external js file -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table id="employeeTable" border="1">
</table>
<script>
$(function() {
buildHtmlTable();
function hideRow(employeeName) {
return $("#employeeTable tr").not(function(index, element) {
return $(element.cells).is(function(i, el) {
return el.textContent === employeeName
});
}).hide();
}
hideRow("Linda");
});
</script>
</body>
</html>
If I understood your question correctly you could do something like I did below. I used setTimeout so you can see the transition from your original output to the updated output:
function buildTable(arr) {
let html = "<table border='1' style='width: 100%'>";
for (let i = 0; i < arr.length; i++) {
html += `<tr>
<td>${arr[i].Name || ''}</td>
<td>${arr[i].Mobile || ''}</td>
<td>${arr[i].Email || ''}</td>
</tr>`;
}
html += "</table>";
return html;
}
function init() {
const LINDA_IDX = 1;
container.innerHTML = buildTable(employees);
setTimeout(function() { //
//Update Linda's phone number
employees[LINDA_IDX].Mobile = 88885555;
//Show just Linda in the table
container.innerHTML = buildTable([employees[LINDA_IDX]])
}, 2000);
}
var employees = [{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
}, {
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
}, {
"Name": "Patrick",
"Email": "patrick#json.com"
}, {
"Name": "Isabella",
"Mobile": 99552222
}];
var container = document.querySelector('#container');
init();
After 2 seconds setTimeout will execute showing Linda's updated info:<br />
<div id="container"></div>

Fill a table according to other cells with js

I'm trying to fill a html table according to the left cells of that table.
So this code below creates a table which is filled by variables :
<table id="myTable" ></table>
<script>
var rightcell = [{name : "Name2", carac: "N2"},{name : "Name8",
carac: "N8"},{name : "Name5", carac: "N5"}]
setName = rightcell.map(a => a.name);
setCarac = rightcell.map(a => a.carac);
var cellobj;
for (var j = 0; j < 10; j++) {
arr2 = [
"Name1" ,"Name2","Name3" ,"Name4","Name5" ,"Name6","Name7" ,"Name8","Name9" ,"Name10"
];
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
}
$('myTable').find('td').each(function () {
if (setName[j] == arr2[j]) {
cell2.innerHTML = setCarac[j]
}
else {
cell2.innerHTML = "nothing"
}
})
</script>
I've also tried to loop in the array but with no success :
<script>
var rightcell = [{name : "Name2", carac: "N2"},{name : "Name8", carac: "N8"},{name : "Name5", carac: "N5"}]
setName = rightcell.map(a => a.name);
setCarac = rightcell.map(a => a.carac);
var cellobj;
for (var j = 0; j < 10; j++) {
arr2 = [
"Name1" ,"Name2","Name3" ,"Name4","Name5" ,"Name6","Name7" ,"Name8","Name9" ,"Name10"
];
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
arr2.forEach(function() {
if (setName[j] == arr2[j]) {
cell2.innerHTML = setCarac[j]
}
else {
cell2.innerHTML = "nothing"
}
})
}
</script>
What I want is for every left cell to check if the right one have the same name in the array of object rightcell and print the carac accordingly.(N1 should be next to Name1 and so on).
Any idea ?
Thanks for the help.
Your code has a lot of errors like using arr2 / cell2 outside of their scopes, not using # for getting id etc. Take a look at the working code:
This works:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<table id="myTable"></table>
<script>
var rightcell = [{
name: "Name2",
carac: "N2"
}, {
name: "Name8",
carac: "N8"
}, {
name: "Name5",
carac: "N5"
}];
var rightCellMap = {};
for (var index = 0; index < rightcell.length; index++) {
rightCellMap[rightcell[index].name] = rightcell[index].carac;
}
arr2 = [
"Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10"
];
for (var j = 0; j < 10; j++) {
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = arr2[j]
}
$('#myTable').find('tr').each(function (index, element) {
var firstTd = $(element).find('td:first')[0];
var firstTdData = firstTd.innerHTML;
if (firstTdData != '' && rightCellMap[firstTdData]) {
firstTd.nextSibling.innerHTML = rightCellMap[firstTdData];
} else {
firstTd.nextSibling.innerHTML = "nothing"
}
})
</script>

JSON to Data Table Mapping

I have my JSON Data in the below format
{
"RegX": {
"LayerA": {
"name": "abcd123",
"url": "htt:cd1234"
},
"LayerB": {
"name": "xyz234",
"url": "ht:bcd12"
}
},
"RegY": {
"Layer1": {
"name": "xyz123",
"url": "ht/abc1234"
},
"Layer2": {
"name": "xy234",
"url": "http://abc12"
}
}
}
I want to display this in a datatable in below format .
TABLE NAME - REGX
NAME URL
LAYERA abcd123 httd1234
LAYERB xyz234 http:cd12
TABLE NAME - REGY
NAME URL
LAYER1 xyz123 http:d1234
LAYER2 xyz234 h/abcd12
Is there a way that i can display single JSON file in two different tables and display proper Row names and Column names also from JSON table ? I am planning to use datatables but not able to find proper implementation to use
var myData = {
"RegX": {
"LayerA": {
"name": "abcd123",
"url": "htt:cd1234"
},
"LayerB": {
"name": "xyz234",
"url": "ht:bcd12"
}
},
"RegY": {
"Layer1": {
"name": "xyz123",
"url": "ht/abc1234"
},
"Layer2": {
"name": "xy234",
"url": "http://abc12"
}
}
};
var tables = Object.keys(myData);
for(var i=0; i<tables.length; i++){
var rows = Object.keys(myData[tables[i]]);
var tbl = document.createElement('table');
document.getElementsByTagName('body')[0].appendChild(tbl);
var thead = tbl.appendChild(document.createElement('thead'));
thead.innerHTML = ("<tr><td>name</td><td>url</td></tr>");
var tbdy = document.createElement('tbody');
tbl.appendChild(tbdy);
for(var j=0; j<rows.length; j++){
var cols = Object.keys(myData[tables[i]][rows[j]]);
var innerHTML = '';
var tr = tbdy.insertRow(j);
for(var k=0; k<cols.length; k++){
innerHTML += "<td>"+myData[tables[i]][rows[j]][cols[k]]+"</td>";
}
tr.innerHTML = innerHTML;
}
}
table, tr , td {
border-collapse: collapse;
border: 1px solid grey;
}
table {
margin: 5px;
}
Try to understand the code and add more to fulfill your needs.
Hope you got it, if not ask me.

Categories

Resources