How to display similar JSON data in one table row - javascript

I want to display similar JSON data in one row.
I'm trying to compare array index with keys index and store in new array
Expected result
this is my code
var array = [{ "english 1": "1", "english 2": "2", "hindi 1": "1", "hindi 2": "2", "gujarati 1": "1", "gujarati 2": "2", "marathi 1": "1", "marathi 2": "2" }]
keys = ['english', 'hindi', 'gujarati', 'marathi'],
grouped = {};
$.each(array, function (i, v) {
$.each(keys,function (ii, vv) {
var o = {};
o[vv] = v[vv];
grouped[vv] = grouped[vv] || [];
grouped[vv].push(o);
});
});
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableData" class="table">
<thead>
<tr>
<th>Language</th>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody id="showData">
</tbody>
</table>

As you have two column where you need to put value you can create separate JSON Array for both column where key will be same . Then, inside your each loop compare if the key matches with keys and only put value if match . Finally , to generate table you can append htmls in some variable using += and append same to your tbody.
Demo Code :
//suppose your json look like below :
var array = [{
english: "1",
hindi: "1",
gujarati: "1",
marathi: "1"
}, {
hindi: "2",
gujarati: "2",
marathi: "2",
english: "2"
}]
keys = ['english', 'hindi', 'gujarati', 'marathi'],
grouped = [];
$.each(keys, function(i, v) {
var o = {}; //create obj
o[v] = new Array() //create array with particular key
$.each(array, function(ii, vv) {
o[v].push(vv[v]) //push value only when key matches
});
grouped.push(o); //push array inside outer array
});
var htmls = "";
$.each(grouped, function(i) {
$.each(grouped[i], function(key, val) {
htmls += "<tr><td>" + key + "</td><td>" + val[0] + "</td><td>" + val[1] + "</td></tr>"; //generate htmls..
});
});
$("#showData").html(htmls) //add same to tbody
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableData" class="table">
<thead>
<tr>
<th>Language</th>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody id="showData">
</tbody>
</table>

Related

Inserting table data under a particular table header from an Object

Given a Javscript Object:
var obj = {
"results": [{
"B": "Row 1 Col 2"
}, {
"A": "Row 1 Col 1"
"B": "Row 2 Col 2"
}, {
"C": "Row 1 Coll 3"
}
}]
I wish to convert it to a table that looks like the following.
<table border="1">
<thead>
<tr>
<th id="A">A</th>
<th id="B">B</th>
<th id="C">C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Col 1</td>
<td>Row 1 Col 2</td>
<td>Row 1 Col 3</td>
</tr>
<tr>
<td></td>
<td>Row 2 Col 2</td>
<td></td>
</tr>
</tbody>
</table>
Which looks like:
Demo Table Data
More precisely, I'm looking for a way to somehow insert the value of a property directly below it.
javascript:
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>';
var rows = obj.results.map(function(item) {
// loop over column keys checking matches to item keys
return '<tr>' +
cols.map(function(key) {
return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>';
}).join('') + '</tr>';
}).join('');
var table = '<table border="1">' + header + rows + '</table>';
Might not be the most elegant way but works
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '\n<thead>\n\t<tr>\n\t\t<th>' + cols.join('</th>\n\t\t<th>') + '</th>\n\t</tr>\n</thead>';
var j = {}
obj.results.map(function(item) {
// loop over column keys checking matches to item keys
cols.map(function(key) {
if(j[key] == undefined)
{
j[key] = []
}
if (item.hasOwnProperty(key))
{
j[key].push(item[key]);
}
})
});
var rows = []
var index = 0
for(let k in j)
{
rows.push([])
for(let e in j[k])
{
rows[index].push(j[k][e])
}
index += 1
}
function transposeArray(array, arrayLength){
var newArray = [];
for(var i = 0; i < array.length; i++){
newArray.push([]);
};
for(var i = 0; i < array.length; i++){
for(var j = 0; j < arrayLength; j++){
newArray[j].push(array[i][j]);
};
};
return newArray;
}
rows = transposeArray(rows, 3)
var rowsStr = "";
for(let k in rows)
{
rowsStr += '\n\t<tr>';
for(let e in rows[k])
{
if(rows[k][e] != undefined)
{
rowsStr += '\n\t\t<td>' + rows[k][e]+ '\t\t</td>'
}
else
{
rowsStr += "\n\t\t<td></td>"
}
}
rowsStr += '\n\t</tr>';
}
var table = '<table border="1">' + header + "\n<tbody>" + rowsStr + "\n</tbody>" + '\n</table>';

I want to make HTML table from array

The task is to fill the table with data from arrays id, name and price.
What am I doing wrong?
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
It doesn't work, because your input data is not organised as an array of objects, but as an object of arrays (which is less OOP).
As I prefer the array of objects as data structure, I would suggest to (temporarily) convert to that structure, and then your loop will work as expected:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(array, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
As an unrelated remark, I would suggest using jQuery more in the process of building the table. This will also avoid problems you might get when your data has < or & characters in it immediately followed by letters, as that would be interpreted as HTML:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var array = data.id.map((id, i) => ({ id, name: data.name[i], price: data.price[i] }));
var i = 0;
$('#tableContainer').empty().append($("<table>").addClass("mainTable").append(
$("<tr>").append(
$("<th>").text("id"),
$("<th>").text("name"),
$("<th>").text("price")
),
...array.map(value =>
$("<tr>").append(
$("<td>").text(value.id),
$("<td>").append($("<img>", { src: value.name })),
$("<td>").text(value.price)
)
)
));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
Your data structure is not iterable. So you need to either change your data structure to be a list [{id: '1111', name: 'name1', price: 1111}], or you need to assume that all lists (id, name, price) are the same length, and use that length for the iteration.
As other answers detail how to use an iterable data structure, I'll handle the other method, where your data is already in this format, and won't change.
For this method, find the length of one property (id, name or price), and iterate through all of them using the index. Here is an example.
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
data.id.forEach((value, index) => {
table += ('<tr>');
table += ('<td>' + data.id[index] + '</td>');
table += ('<td><img src="' + data.name[index] + '"></td>');
table += ('<td>' + data.price[index] + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
You're processing the data as if it were structured as a single array, like this:
data = [
{
id: 1986,
name: "name1",
price: 1148
}
]
However, your data contains three arrays, not one:
data = {
id: [...],
name: [...],
price: [...],
}
If the data was structured like the first example, then value would contain an object for each array element, with the properties id, name and price available.
An option is to convert the first data structure to the second:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
id: id,
name: data.name[index],
price: data.price[index]
}))
Then, use the mappedData and access the properties as you're already doing, as follows:
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var mappedData = data.id.map((id, index) => ({
id: id,
name: data.name[index],
price: data.price[index]
}))
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(dataMapped, function(index, value){
table += ('<tr>');
table += ('<td>' + value.id + '</td>');
table += ('<td><img src="' + value.name + '"></td>');
table += ('<td>' + value.price + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
var data = {"id":["1986","1990","1989","1985","1988","1987"],"name":["name1","name2 ","name3 ","name4","латунь матовая ","name5"],"price":[1148,1396,2775,1270,1396,1270]};
var i = 0;
var table = '<table class="mainTable"><tr><th>id</th><th>name</th><th>price</th></tr>';
$.each(data["id"], function(index, value){
table += ('<tr>');
table += ('<td>' + value + '</td>');
table += ('<td><img src="' + data["name"][index] + '"></td>');
table += ('<td>' + data["price"][index] + '</td>');
table += ('</tr>');
});
table += '</table>';
$('#tableContainer').html(table);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableContainer">
</div>
There ways to iterate the data as you defined it but I think it's better to define it in a proper way, as an array of entities ($.each is to iterate through an array):
[
{
"id": "1986",
"name": "name1",
"price": 1148
},
{
"id": "1990",
"name": "name2",
"price": 1396
},
];
Without changing the input you can do this.
var data = {
"id": ["1986", "1990", "1989", "1985", "1988", "1987"],
"name": ["name1", "name2 ", "name3 ", "name4", "латунь матовая ", "name5"],
"price": [1148, 1396, 2775, 1270, 1396, 1270]
};
document.getElementById("tableContainer").innerHTML = data.id
.map((id,i) => `<tr><td>${id}</td>
<td><img src="${data.name[i]}"></td>
<td>${data.price[i]}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table class="mainTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody id="tableContainer"></tbody>
</table>
</div>
I also recommmend you change the input to an array of objects. It makes the parsing simpler
var data = [
{ "id": "1986", "name": "name1", "price": 1148},
{ "id":"1990", "name": "name2", "price": 1396},
{ "id":"1989", "name": "name3", "price": 2775},
{ "id":"1985", "name": "name4", "price": 1270},
{ "id":"1988", "name": "латунь матовая ", "price": 1396},
{ "id":"1987", "name": "name5", "price": 1270}
];
document.getElementById("tableContainer").innerHTML = data
.map(({id,name,price}) => `<tr><td>${id}</td>
<td><img src="${name}"></td>
<td>${price}</td></tr>`).join("")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<table class="mainTable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
</tr>
</thead>
<tbody id="tableContainer"></tbody>
</table>
</div>

How to loop two objects in one table

I have data like this one but find hard to loop both objects and get data into one table where th to be company and td to be their drivers
{…}
driver: Array(18) [ {…}, {…}, {…}, … ]
company: "TEST"
{…}
driver: Array(10) [ {…}, {…} ]
company: "TEST 1"
​
i tried like this one but is do not work properly
$.each(response.allDrivers, function(key, value){
var thead = '';
thead += '<th>'+value.company+'</th>';
$('#table-allDrivers thead tr').append(thead);
$.each(value.driver, function(id,name){
var tbody = '';
tbody = '<tr> <td>'+name.driver+'<td></tr>';
$('#table-allDrivers tbody').append(tbody);
})
});
result im getting is like this one
<thead>
<tr>
<th>TEST</th>
<th>TEST 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Driver 1</td>
<td></td>
</tr>
<tr>
<td>Driver 2</td>
<td></td>
</tr>
<tr>
<td>Driver 3</td>
<td></td>
</tr>
<tr>
<td>Driver 4</td>
<td></td>
</tr>
</tbody>
Suppose you have 2 driver (driver1 and driver2) but maybe more. Find the one with more elements and iterate from that (I assumed driver1 has more elements);
var markup = "";
for( let i = 0 ; i < driver1.length; i++)
{
if (i < driver2.length)
{
markup += '<tr><td>'+driver1[i].+'</td><td>'+driver2[i]+'</td><tr>';
}
else
{
markup += '<tr><td>'+driver1[i].+'</td><td></td><tr>';
}
}
$('#table-allDrivers tbody').append(markup);
I think this would show the correct result even if this is not the best way but i tried with as much information i got.
It's a little different from how you have it there, but you can try something like this—run the snippet to see the result:
var arr = [
{
driver: ['item1', 'item2', 'item3'],
company: "Company1"
},
{
driver: ['item1', 'item2'],
company: "Company2"
}
]
var thead = document.querySelector('table thead tr')
var tbody = document.querySelector('table tbody')
arr.forEach(function(item) {
thead.innerHTML += '<th>' + item.company + '</th>';
item.driver.forEach(function(driverItem) {
tbody.innerHTML += '<tr></tr>';
})
tbody.querySelectorAll('tr').forEach(function(tr, i) {
tr.innerHTML += item.driver[i] ? '<td>' + item.driver[i] + '</td>' : '<td></td>' //catering for colspan layout
tr.innerHTML === '<td></td>' ? tr.remove() : '' //removing empty <tr> elements
})
})
<table>
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
The right way to use HTML Tables with multiple values for each cell is to use rowspan or colspan attribute, which in your case each company has multiple drivers. To achieve that:
Javascript:
// Your data
const allDrivers = [
{
drivers: ['driverComapnyA-1', 'driverComapnyA-2', 'driverComapnyA-3'],
company: 'Comapny A',
},
{
drivers: [
'driverComapanyB-1',
'driverComapanyB-2',
'driverComapanyB-3',
'driverComapanyB-4',
],
company: 'Comapny B',
},
];
allDrivers.forEach((item, index) => {
if (index == 0) {
// Make sure to setup tbody markup once
$('#table-allDrivers').append('<tbody></tbody>');
}
const tableBody = $('#table-allDrivers').find('tbody');
tableBody.append(
'<tr data-index="' +
index +
'"><th rowspan="' +
item.drivers.length +
'">' +
item.company +
'</th></tr>'
);
item.drivers.forEach((driver, i) => {
if (i == 0) {
// if its the first item in drivers array then add it as a child in <tr>
tableBody
.find('[data-index="' + index + '"')
.append('<td>' + driver + '</td>');
} else {
// otherwise just append it to <tbody>
tableBody.append('<tr><td>' + driver + '</td></tr>')
}
});
});
Markup:
<table id="table-allDrivers"></table>
And here's a working fiddle: https://jsfiddle.net/khzway7u/

Specific table cells into array

I have a table below that consist of a product. However, I only want to insert the first 4 cells of the each row as an Array. So the array would be [1, Adidas, 2 , $100, 2, Nike, 1 , $50]
Product ID | Product Name | Qty | Price |
1 | Adidas | 2 | $100 | Delete btn
2 | Nike | 1 | $50 | Delete btn
I tried and got out this jquery code, however, it insert all of the td of each row into the array, which is not what I want.
How do I modify this set of code to only insert first 4 and exclude the last cell? Thank you.
$("#checkoutList > tbody > tr").each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
Use jQuery each() and map() method to genearate the array. To exclude last column use combination of :not() and :last-child pseudo-class selector.
// array for result
var res = [];
// iterate over the tr
$("table > tbody > tr").each(function() {
// push the content array to `res`
res.push(
// get all td except last and generate content array
$('td:not(:last-child)', this).map(function() {
// get content and trim
return $(this).text().trim();
// get the result as an array
}).get()
);
});
var res = [];
$("table > tbody > tr").each(function() {
res.push($('td:not(:last-child)', this).map(function() {
return $(this).text().trim();
}).get());
});
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<td>
Product ID</td>
<td>Product Name</td>
<td>Qty</td>
<td>Price</td>
<td>Price</td>
</thead>
<tbody>
<tr>
<td>
1</td>
<td>Adidas</td>
<td>2</td>
<td>$100</td>
<td>Delete btn</td>
</tr>
<tr>
<td>
2</td>
<td>Nike</td>
<td>1</td>
<td>$50</td>
<td>Delete btn</td>
</tr>
</tbody>
</table>
Try this one:
tableData.slice(0, 4);
You will store in tableData, only the first 4 cells...
Array.slice()
It's very simple to do these jobs with pure JS. Let's first create our test table as it should be and then obtain the desired array from the test table.
function tableMaker(o,h){
var keys = Object.keys(o[0]),
rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
: "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
return "<table>" + rows + "</table>";
}
var tableData = [{"Product ID": 1, "Product Name": "Adidas", Qty: 2, Price: 100, Delete: "<button>Delete</button>"},
{"Product ID": 2, "Product Name": "Nike", Qty: 1, Price: 50, Delete: "<button>Delete</button>"},
{"Product ID": 3, "Product Name": "Puma", Qty: 4, Price: 79, Delete: "<button>Delete</button>"},],
ptContainer = document.getElementById("ptContainer"),
productTable,
productArray = [];
ptContainer.innerHTML = tableMaker(tableData,true);
productTable = document.getElementsByTagName("table")[0];
for (var i=1; i<productTable.rows.length; i++){
productArray.push(productTable.rows[i].cells[0].textContent,
productTable.rows[i].cells[1].textContent,
productTable.rows[i].cells[2].textContent);
}
console.log(productArray);
<div id="ptContainer"></div>
Or you can even simplify the last part like;
for (var i=1; i<productTable.rows.length; i++){
productArray.push(...[...productTable.rows[i].cells].slice(0,3).map(c => c.textContent));
}

Inserting table <td> cell under a particular header <th> from an Object

Given a Javscript Object:
var obj = {
"results": [{
"B": "Row 1 Col 2"
}, {
"A": "Row 2 Col 1"
"B": "Row 2 Col 2"
}, {
"C": "Row 3 Coll 3"
}
}]
I wish to convert it to a table that looks like the following.
<table border="1">
<thead>
<tr>
<th id="A">A</th>
<th id="B">B</th>
<th id="C">C</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Row 1 Col 2</td>
<td></td>
</tr>
<tr>
<td>Row 2 Col 1</td>
<td>Row 2 Col 2</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>Row 3 Col 3</td>
</tr>
</tbody>
</table>
Which looks like:
More precisely, I'm looking for a way to somehow insert the value of a property directly below it. And creating a new header as when a new property emerges while successively reading the object. This is a better way of approaching the problem I feel, as it is more versatile for an arbitrary object.
This is why I was wondering if there was any HTML tag or jQuery way such that I can directly insert a cell under a particular header of my choice instead of calculating and inserting appropriate number of "<td></td>" till I get to the right cell.
Fiddle: https://jsfiddle.net/kqsozme5/2/
Following doesn't care how many columns there are, and works on totally arbitrary object config.
It sorts the column names prior to looping through data again to build rows and creates empty cells as necessary
// create array of column keys and sort
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>';
var rows = obj.results.map(function(item) {
// loop over column keys checking matches to item keys
return '<tr>' +
cols.map(function(key) {
return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>';
}).join('') + '</tr>';
}).join('');
var table = '<table border="1">' + header + rows + '</table>';
var obj = {
"results": [{
"B": "Row 1 Col 2"
}, {
"A": "Row 2 Col 1",
"B": "Row 2 Col 2"
}, {
"C": "Row 3 Coll 3"
}]
};
// create array of column keys and sort
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>';
var rows = obj.results.map(function(item) {
// loop over column keys checking matches to item keys
return '<tr>' +
cols.map(function(key) {
return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>';
}).join('') + '</tr>';
}).join('');
var table = '<table border="1">' + header + rows + '</table>';
$('body').append(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Html:
<tbody id = "idTBody">
Jquery:
for(var result in obj.results)
{
for(var col in obj.results[result])
{
$("#idTBody").append("<tr>");
if(col == 'A'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
else {$("#idTBody").append("<td></td>");}
if(col == 'B'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
else {$("#idTBody").append("<td></td>");}
if(col == 'C'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
else {$("#idTBody").append("<td></td>");}
$("#idTBody").append("</tr>");
}
}
why don't use arrays
var object = {
result: [['a', 'b', 'c'],
['', 'rows1 col2', ''],
['row2 col1', 'row2 col2', '']]
}
it's easy to convert to tables.
Assuming Your Object is :
var obj = {
"results": [{
"A": "",
"B": "Row 1 Col 2",
"C": ""
}, {
"A": "Row 2 Col 1",
"B": "Row 2 Col 2",
"C": ""
}, {
"A": "",
"B": "",
"C": "Row 3 Coll 3"
}
}]
HTML Would Be:
<table id="trialTable" border="1">
<thead>
<tr>
<th id="A">A</th>
<th id="B">B</th>
<th id="C">C</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQuery will Be:
var tbody = $("#trialTable > tbody");
tbody.empty();
$.each(obj.results, function(index, data) {
var tr = $("<tr>");
var td = $("<td>");
tr.append($('<td>', {
text: data.A
}));
tr.append($('<td>', {
text: data.B
}));
tr.append($('<td>', {
text: data.C
}));
tbody.append(tr);
});
you will get your expected output.As far as i know, using jQuery instead of simple javascript is always easy and less confusing.

Categories

Resources