I've created a sample application which converts html table into JSON. The problem is that the JSON is not having duplicate values also i want to remove the last two columns from the JSON.
My JSON which has been generated is given below
[
{
"Person Name":"Smith",
"Score":"disqualified",
"Price":"150",
"Tax":"41"
},
{
"Person Name":"Jackson",
"Score":"94",
"Price":"250",
"Tax":"81"
},
{
"Person Name":"Doe",
"Score":"80",
"Price":"950",
"Tax":"412"
},
{
"Person Name":"Johnson",
"Score":"67",
"Price":"750",
"Tax":"941"
}
]
But my expected JSON is like
[
{
"Person Name":"Jill",
"Person Name":"Smith",
"Score":"disqualified"
},
{
"Person Name":"Eve",
"Person Name":"Smith",
"Score":"94"
},
{
"Person Name":"John",
"Person Name":"Smith",
"Score":"80"
},
{
"Person Name":"Adam",
"Person Name":"Smith",
"Score":"67"
}
]
Can anyone please tell me how to generate the above JSON from the table
My code is as given below.
html code
<table id='example-table'>
<thead>
<tr>
<th>Person Name</th>
<th>Person Name</th>
<th data-override="Score">Points</th>
<th>Price</th>
<th>Tax</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td data-override="disqualified">50</td>
<td>150</td>
<td>41</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
<td>250</td>
<td>81</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
<td>950</td>
<td>412</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
<td>750</td>
<td>941</td>
</tr>
</tbody>
</table>
<button id="convert-table" >Convert!</button>
javascript code
$('#convert-table').click( function() {
var table = $('#example-table').tableToJSON();
console.log(table);
alert(JSON.stringify(table));
});
DEMO (JSFiddle)
something like that would work (not really nice, but)
Explanation :
You can use ignoreColumns to avoid taking columns 3 and 4.
You can use headings to change the "headers" (keys in the json file). But this will take also the first line (the one with the TH).
So we have to remove that first line after building the json array.
$('#convert-table').click( function() {
var $table = $('#example-table');
var table = $table.tableToJSON(
{
ignoreColumns:[3, 4],
headings: ['FirstName', 'LastName', 'Score']
});
var newTable = $.map(table, function(e){
return (e.FirstName == "Person Name") ? null : e;
});
console.log(newTable);
alert(JSON.stringify(newTable));
});
see jsfiddle
EDIT
If the number of columns with Person Name is dynamic, you could do something like that (assuming you never want the two last rows)
function convertToTable(el, numberOfColumns, columnNames) {
var columnsToIgnore = [numberOfColumns-2, numberOfColumns-1];
var table = el.tableToJSON(
{
ignoreColumns:columnsToIgnore,
headings: columnNames
});
var result = $.map(table, function(e){
return (e['Person Name0'] == "Person Name") ? null : e;
});
alert(JSON.stringify(result));
}
$('#convert-table').click( function() {
var $table = $('#example-table');
var columns = $table.find('th');
var numberOfColumns = columns.length;
var columnNames = columns.map(function(index) {
var text = $(this).text();
return text == 'Person Name' ? text + index : text;
}).get();
convertToTable($table, numberOfColumns, columnNames);
});
see JsFiddle
You can't have duplicate keys, but you can use an array of names instead. Example:
{
"PersonNames":["John","Smith"],
"Score":"80"
},
to remove last two fields use "ignoreColumns" option
var table = $('#example-table').tableToJSON({
ignoreColumns:[2,3]
});
and make headers unique
<th>Person Name</th>
<th>Person SurName</th>
Try this:
$('#convert-table').click( function() {
var table = $('#example-table').tableToJSON({
ignoreColumns:[3,4]}
);
console.log(table);
alert(JSON.stringify(table));
});
Jsfiddle: http://jsfiddle.net/robertrozas/9VX6Z/
From row a way to format html-data.
$("#del_player").on("click", function() {
var row_to_del = $("#table_player tbody tr[active=true]");
var arr = [];
$.each(row_to_del, function(key, val){
arr.push(val.outerText.split('\t'));
});
console.log(JSON.stringify(arr));
})
Related
Active learner here, trying to figure out how to create a JSON object out of HTML table. I only want the value of one specific TD and want to give each value an incrementing number as a key. I'd like an output like below. My table has a TD for the city names, but it does not have one with a incrementing numerical value so I'd need to add that another way.
{
"mycities" : [
{
"Seattle" : "1",
"Chicago" : "2",
"New York" : "3"
"Pitt" : "4",
"LA" : "5",
"Fresno" : "6"
},
]
}
Here is what my table looks like:
<table>
<thead>
<tr>
<th>city name</th>
<th>other city info</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seattle</td>
<td>Lots of rain</td>
</tr>
etc,etc,etc
</tbody>
</table>
I've tried using a replacer function but haven't got it figured out after much googling. Any help is appreciated!
$(document).ready(function(){
$("body").on("click",".submitButtonPri",function(){
count= 1;
function replacer(key, value) {
if (typeof value === 'string') {
return count;
}
return value;
}
var myRows = [];
var $headers = $(".rightDash > table thead th");
var $rows = $(".rightDash > table tbody tr").each(function(index) {
$cells = $(this).find("td.titlePri");
myRows[index] = {};
$cells.each(function(cellIndex) {
myRows[index][$($cells[cellIndex]).text()] = $(this).text();
});
count++;
});
var myObj = {};
myObj.myrows = myRows;
console.log(JSON.stringify(myObj,replacer));
});
});
Use reduce to iterate over the trs in the body, using the text content of the first td in the tr as the city name. The third argument to the function provided to reduce represents the iteration index:
const cityData = [...document.querySelectorAll('tbody > tr')]
.reduce((a, tr, i) => {
a[tr.children[0].textContent] = i + 1;
return a;
}, {});
console.log(
{ mycities: [
cityData
]}
);
<table>
<thead>
<tr>
<th>city name</th>
<th>other city info</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seattle</td>
<td>Lots of rain</td>
</tr>
<tr>
<td>Chicago</td>
<td>Lots of rain</td>
</tr>
<tr>
<td>New York</td>
<td>Lots of rain</td>
</tr>
</tbody>
</table>
You can start with this simple script:
$('td').each(function(index, obj) {console.log(index, $(this).html())});
It returns all what you need and you just need assemble JSON by any way
I've been searching on how to achieve this. I got a lot of info from this site, but all couldn't help.
I'm trying to populate a table with the data I got from PHP File Using Ajax
I've been able to get the data, at least into the console. But when i try sending it to the the table, nothing is shown. No errors shown, Just blank.
console.log(newarr)
brings
gives this answer (image)
But when I do this $("#report").html(newarr);, nothing happens.
Here is the code:
ajax
$.post('./process/assetReport.php', data, function(data) {
genData = JSON.parse(data);
var newarr;
for (var key in genData) {
if (data.hasOwnProperty(key)) {
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
php
foreach($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
The table I need to populate
<table class="table" id="reportTable">
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id="report">
</tbody>
<tfoot>
<tr>
<td><button type="button" class="btn btn-success" id="printReport"><i class="glyphicon glyphicon-print"></i> Print</button></td>
</tr>
</tfoot>
</table>
I hope my question is explanatory enough
Thank you
I have created a stub of a JSON array, and shown how to loop through it appending rows to your table as you go. I excluded your key check, as I wasn't sure the relevance. A variation of this code should reside in the callback to your $.post()
data = [{
asset: "steve",
staff: "steve",
cost: '$999,999.99'
}, {
asset: 'bob',
staff:"bob",
cost: '$0.99'
}];
var $row = $("<tr><td></td><td></td><td></td></tr>"); //the row template
var $tr;
$.each(data, function(i, item) {
$tr = $row.clone(); //create a blank row
$tr.find("td:nth-child(1)").text(item.asset); //fill the row
$tr.find("td:nth-child(2)").text(item.staff);
$tr.find("td:nth-child(3)").text(item.cost);
$("#report").append($tr); //append the row
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id='report'>
<tbody>
</table>
I think you need to user genData[0] instead of genData as your are using $useData[] inside php or user $useData instead of $useData[]
So the code should be look like followings:
$.post( './process/assetReport.php', data, function (data) {
genData = JSON.parse(data);
var newarr;
for(var key in genData[0]) {
if(data.hasOwnProperty(key)){
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
And the php:
foreach ($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
config.previewData = [
{
Cartridges:27989,
Total Accounts:294,
Metrices:"MVC",
Toner Cartridges:5928,
INK Cartridges:22061
},
{
Cartridges:56511,
Total Accounts:376,
Metrices:"SMB",
Toner Cartridges:15253,
INK Cartridges:41258
},
{
Cartridges:84,500,
Total Accounts:670,
Metrices:"Grand Total",
Toner Cartridges:21,181,
INK Cartridges:63,319
},
]
and my html code like this
<table class="table table-striped">
<thead>
<tr role="row">
<th data-ng-repeat="(key, val) in config.previewData[0]">
{{ key}}
</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="row in config.previewData">
<td data-ng-repeat="column in row">
{{column}}
</td>
</tr>
</tbody>
</table>
this code will print perfect like below image
now i want to transpose this table into rows to columns and columns to rows.
Is this possible with dynamic table because my object is dynamic not fixed.
Help me if anyone knows how to do this.
After transpose table looks like this
Using the same assumptions your example codes does (i.e. config.previewData always contains at least one object, and all objects have the same properties...)
<table class="table table-striped">
<tbody>
<tr data-ng-repeat="(key, val) in config.previewData[0]">
<th>
{{ key }}
</th>
<td data-ng-repeat="row in config.previewData">
{{ row[key] }}
</td>
</tr>
</tbody>
</table>
Using reduce, you can have something like this to transpose your data, which can then be used to iterate over using ng-repeat very easily!
Example snippet (in Pure JS for simplification):
var previewData = [{
"Cartridges": 27989,
"Total Accounts": 294,
"Metrices": "MVC",
"Toner Cartridges": 5928,
"INK Cartridges": 22061
},
{
"Cartridges": 56511,
"Total Accounts": 376,
"Metrices": "SMB",
"Toner Cartridges": 15253,
"INK Cartridges": 41258
},
{
"Cartridges": 84500,
"Total Accounts": 670,
"Metrices": "Grand Total",
"Toner Cartridges": 21181,
"INK Cartridges": 63319
}
]
var transpose = previewData.reduce(function(arr, obj) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
arr[key] = arr[key] || []
arr[key].push(obj[key])
}
}
return arr
}, {})
console.log(transpose)
this is the only (dirty) way i could think out
<tr>
<td data-ng-repeat="row in previewData">{{row['Metrices']}}</td>
</tr>
<tr>
<td data-ng-repeat="row in previewData">{{row['Total Accounts']}}</td>
</tr>
<tr>
<td data-ng-repeat="row in previewData">{{row['Toner Cartridges']}}</td>
</tr>
...... and so on
other options: Transposing JSON
If you have a 2-D array which can be logged into console by the function
tab = [[2,3,4],[-4,6,0],[1,0,9]]
console.table(tab)
You can log the transpose of it by using the following function:
function transpose_table(tab) {
let columns = tab.length;
let rows = tab[0].length;
let trans = [];
for (i=0; i<rows; i++) {
trans.push([]);
}
for (i=0; i<columns; i++) {
for (j=0; j<rows; j++) {
trans[j][i] = tab[i][j];
}
}
return trans;
}
Now run:
console.table(transpose_table(tab))
I've a bit of experience coding in php but am fairly new to js. What I'm trying to do in js is create a simple order form, each line is to have a text box indicating the quantity to be ordered, product name and product price, with the latter to be populated from product array prod. My fairly rudimentary first attempt appears below, which needless to say doesn't work.
<body onload="populate()">
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
function populate(){
var prod; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i=0; i<prod.length; i++)
{
var newTr = table.insertRow(-1);
var numOrdered=document.createElement('input');
numOrdered.type='text';
numOrdered.id= "product "+i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(num);
newTr.insertCell(-1).appendChild(document.createTextNode(prod["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod["price"]));
}
}
</script>
</body>
Any and all help appreciated.
have a look at the snippet at the bottom.
what's changed is:
in this line you targeted the wrong id, should have been 'demo'
var table = document.getElementById("theTable");
you also needed to reference the correct value in your array inside the loop:
document.createTextNode(prod["name"]);
to:
document.createTextNode(prod[i]["name"]);
and lastly this line:
newTr.insertCell(0).appendChild(num);
to:
newTr.insertCell(0).appendChild(numOrdered);
hope this helps.
function populate() {
var prod = [{
name: 'box',
price: 20
}, {
name: 'plane',
price: 40
}]; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i = 0; i < prod.length; i++) {
var newTr = table.insertRow(-1);
var numOrdered = document.createElement('input');
numOrdered.type = 'text';
numOrdered.id = "product " + i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(numOrdered);
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["price"]));
}
}
populate();
<table id="theTable">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
Try This code:
I am using jQuery, to create, append and iterating the array(each Loop).It is a better and effective way. Please use jQuery for DOM manipulation.
HTML:
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
CSS:
table,td{display:block}
th{width:100px}
td{margin:10px}
JS:
var prod=[{product:'samsung',price:100},{product:'apple',price:200},{product:'micromax',price:300}];
(function($){
$.each(prod,function(index,value){
$('#demo th:eq(0)').append("<td><input type='text'></td>");
$('#demo th:eq(1)').append("<td>"+value.product.toUpperCase()+"</td>");
$('#demo th:eq(2)').append("<td>"+value.price+"</td>")
});
})(jQuery);
Here is the JSFiddle Link:
https://jsfiddle.net/Dee0565/8vww1pwf/
I need to get data from a table and store it in an array. Each row of the table should be a new array within an array. Basically the html looks like this:
<table id="contactlisttable">
<tr>
<th>Name</th>
<th>Title</th>
<th>Phone</th>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Joey</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Anthony</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
</table>
ect...
Here is my code
jQuery(document).ready(function(){
$(function(){
var $table = $("#contactlisttable"),
$headerCells = $table.find("tr th"),
$myrows = $table.find("tr"); // Changed this to loop through rows
var headers = [],
rows = [];
$headerCells.each(function() {
headers[headers.length] = $(this).text();
});
$myrows.each(function() {
$mycells = $myrows.find( "td.contactlist" ); // loop through cells of each row
cells = []
$mycells.each(function() {
cells.push($(this).text());
});
if ( cells.length > 0 ) {
rows.push(cells);
}
});
console.log(headers);
console.log(rows);
});
});
my current code out puts
[["Waddell, Joey", "webdesigner", "", 15 more...], ["Waddell, Joey", "webdesigner", "", 15 more...],
the desired output would be:
["Name","Title","Phone"]
[["Joey","webdesigner","555555"]
["Anthony","webdesigner","555555"]]
I think this can be simpler:
Live Demo
JS
$(function(){
var results = [];
var row = -1;
$('#contactlisttable').find('th, td').each(function(i, val){
if(i % 3 === 0){ //New Row?
results.push([]);
row++;//Increment the row counter
}
results[row].push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)
});
console.log(results);
});
EDIT
Here's an even better solution (IE9+ compatible). It accounts for variable row lengths unlike my previous solution.
Live Demo
JS
//IE9+ compatable solution
$(function(){
var results = [], row;
$('#contactlisttable').find('th, td').each(function(){
if(!this.previousElementSibling){ //New Row?
row = [];
results.push(row);
}
row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)
});
console.log(results);
});