How to loop two objects in one table - javascript

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/

Related

jQuery sum the values of table rows

hello i have this table
i want to get the total of each row in the total column
jQuery
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var leads = $('#leads');
var budget_total_year = $('#full_year_cost');
var budget_total_month = $('#share_cost');
var budget_per_lead = $('#cost_per_lead');
leads.append('<th>' + value.olxTotal + '</th>');
budget_total_year.append('<th>' + value.budget_total_year + '</th>');
budget_total_month.append('<th>' + value.budget_total_month + '</th>');
budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
})
})
HTML
<tbody id="tableData-marketMonth">
<tr id="leads">
<th>Leads</th>
</tr>
<tr id="full_year_cost">
<th>Full Year Cost</th>
</tr>
<tr id="share_cost">
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr id="cost_per_lead">
<th>Cost per Lead</th>
</tr>
</tbody>
i was going to calculate the total through php but i though it can be easier
using jQuery just putting the sum of each row at the end
Thank you very much
Create variables before the loop. add to the variables in the loop and then assign the sum at the end.
$.get('/dashboard/costs', function(data){
var sumLeads = 0;
var sumFullYearCost = 0;
var sumShareCost = 0;
var sumCostPerLead = 0;
var tr_leads = $('#leads');
var tr_budget_total_year = $('#full_year_cost');
var tr_budget_total_month = $('#share_cost');
var tr_budget_per_lead = $('#cost_per_lead');
$.each(data,function(i,value){
tr_leads.append('<th>' + value.olxTotal + '</th>');
tr_budget_total_year.append('<th>' + value.budget_total_year + '</th>');
tr_budget_total_month.append('<th>' + value.budget_total_month + '</th>');
tr_budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
sumLeads += value.olxTotal;
sumFullYearCost += value.budget_total_year;
sumShareCost += value.budget_total_month;
sumCostPerLead += value.budget_per_lead;
});
tr_leads.append('<th>' + sumLeads + '</th>');
tr_budget_total_year.append('<th>' + sumFullYearCost + '</th>');
tr_budget_total_month.append('<th>' + sumShareCost + '</th>');
tr_budget_per_lead.append('<th>' + sumCostPerLead + '</th>');
});
Example for leads row using Array.map and Array.reduce. Use jQuery to get the td elements.
var leads = $('#leads');
const total = leads.children('td').toArray().map(x=>Number(x.innerHTML)).reduce((sum, x) => sum + x)
leads.append(`<th>${total}</th>`);
Try something like this.
$('#tableData-marketMonth tr').each(function () {
var row = $(this);
var rowTotal = 0;
$(this).find('th').each(function () {
var th = $(this);
if ($.isNumeric(th.text())) {
rowTotal += parseFloat(th.text());
}
});
row.find('th:last').text(rowTotal);
});
NOTE: change 'th' to 'td' if you have td's. Looking at your jquery, it looks like you are appending th's.
You can use my written code to vote if you like it...
HTML
<table>
<thead>
<tr>
<th>MAX ATK</th>
<th>MAX DEF</th>
<th>MAX HP</th>
<th>Overall</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat">8170</td>
<td class="combat">6504</td>
<td class="combat">6050</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">8500</td>
<td class="combat">10200</td>
<td class="combat">7650</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">9185</td>
<td class="combat">7515</td>
<td class="combat">9185</td>
<td class="total-combat"></td>
</tr>
</tbody>
</table>
jquery
$(document).ready(function () {
//iterate through each row in the table
$('tr').each(function () {
//the value of sum needs to be reset for each row, so it has to be set inside the row loop
var sum = 0
//find the combat elements in the current row and sum it
$(this).find('.combat').each(function () {
var combat = $(this).text();
if (!isNaN(combat) && combat.length !== 0) {
sum += parseFloat(combat);
}
});
//set the value of currents rows sum to the total-combat element in the current row
$('.total-combat', this).html(sum);
});
});

How to show total of dynamically added column using jquery

I have made a shopping cart where I added row based on autocomplete search. and based on quantity price changed. But I want to find the total of subtotal..I have written the update part. But it's showing 0 instead of actual value. Can anyone help me to find it out what's the wrong in my jQuery code..Thank You!
$('#searchName').autocomplete({
source: '{!! asset('nameAutocomplete') !!}',
select:function(suggestion,ui){
event.preventDefault();
var $tbody = $('#example tbody');
$tbody.append('<tr><td class="id">' + ui.item.id +
'</td><td class="name">' + ui.item.value +
'</td><td class="price">' + ui.item.price +
'</td><td><input type="text" class="quantity" value="1"/></td><td><input type="text" class="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');
$('.quantity').on('keyup',function(){
var tot = $(this).parent().prev().html() * this.value;
$(this).parent().next().find('.total').val(tot);
console.log(calculateSum());
});
function calculateSum(){
var sum = 0;
$(".total").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
return sum;
}
}
});
Here is table part :
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
$(".total") is an input, so you should use var value = $(this).val();, not var value = $(this).text();

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.

How can I append <td> dynamically according to the number of values in json

I am creating a program where I get value from json and I want to show that value in a table. I am getting all the values in console but only the last arrays value is displayed in the table. So I want to append the dynamically so that it will create new td according to the values in json file.
HTML Code:
<tr>
<td>Count:</td>
<td id="count"></td>
</tr>
<tr>
<td>Created:</td>
<td id="created"></td>
</tr>
<tr>
<td>Lang:</td>
<td id="lang"></td>
</tr>
<tr>
<td>ID:</td>
<td id="id"></td>
</tr>
<tr>
<td>Name:</td>
<td id="Name"></td>
</tr>
<tr>
<td>Rate:</td>
<td id="Rate"></td>
</tr>
<tr>
<td>Date:</td>
<td id="Date"></td>
</tr>
<tr>
<td>Time:</td>
<td id="Time"></td>
</tr>
<tr>
<td>Ask:</td>
<td id="Ask"></td>
</tr>
<tr>
<td>Bid:</td>
<td id="Bid"></td>
</tr>
In this file I have only one value for count, created and lang. Whereas I have 29 values for the rest of the fields.
Javascript file:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDARS%22,%20%22USDAUD%22,%20%22USDBHD%22,%20%22USDBRL%22,%20%22USDGBP%22,%20%22USDCNY%22,%20%22USDHRK%22,%20%22USDDKK%22,%20%22USDEGP%22,%20%22USDSVC%22,%20%22USDEEK%22,%20%22USDETB%22,%20%22USDEUR%22,%20%22USDHKD%22,%20%22USDHUF%22,%20%22USDINR%22,%20%22USDIDR%22,%20%22USDJPY%22,%20%22USDKWD%22,%20%22USDNZD%22,%20%22USDNOK%22,%20%22USDPKR%22,%20%22USDPHP%22,%20%22USDPLN%22,%20%22USDRUB%22,%20%22USDSGD%22,%20%22USDZAR%22,%20%22USDSEK%22,%20%22USDCHF%22%29&format=json&env=store://datatables.org/alltableswithkeys', function (json) {
// Set the variables from the query array
//alert(json.query.results.rate.length);
var count = json.query.count;
console.log('Count : ', count);
var created = json.query.created;
console.log('Created : ', created);
var lang = json.query.lang;
console.log('Lang : ', lang);
for(i=0; i<json.query.results.rate.length; i++)
{
var id = json.query.results.rate[i].id;
console.log('ID : ', id);
var name = json.query.results.rate[i].Name;
console.log('Name : ', name);
var rate = json.query.results.rate[i].Rate;
console.log('Rate : ', rate);
var date = json.query.results.rate[i].Date;
console.log('Date : ', date);
var time = json.query.results.rate[i].Time;
console.log('Time : ', time);
var ask = json.query.results.rate[i].Ask;
console.log('Ask : ', ask);
var bid = json.query.results.rate[i].Bid;
console.log('Bid : ', bid);
//}
// Set the table td text
$('#count').text(count);
$('#created').text(created);
$('#lang').text(lang);
$('#id').text(id);
$('#Name').text(name);
$('#Rate').text(rate);
$('#Date').text(date);
$('#Time').text(time);
$('#Ask').text(ask);
$('#Bid').text(bid);
}
});
JSON data (source):
{"query":{"count":29,"created":"2015-07-07T07:33:27Z","lang":"nl-NL","results":{"rate":[{"id":"USDARS","Name":"USD/ARS","Rate":"9.1173","Date":"7/7/2015","Time":"8:33am","Ask":"9.1214","Bid":"9.1173"},{"id":"USDAUD","Name":"USD/AUD","Rate":"1.3374","Date":"7/7/2015","Time":"8:33am","Ask":"1.3376","Bid":"1.3374"},{"id":"USDBHD","Name":"USD/BHD","Rate":"0.3770","Date":"7/7/2015","Time":"8:33am","Ask":"0.3790","Bid":"0.3770"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.1391","Date":"7/7/2015","Time":"8:33am","Ask":"3.1392","Bid":"3.1391"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6428","Date":"7/7/2015","Time":"8:33am","Ask":"0.6428","Bid":"0.6428"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.2098","Date":"7/7/2015","Time":"8:33am","Ask":"6.2104","Bid":"6.2098"},{"id":"USDHRK","Name":"USD/HRK","Rate":"6.8687","Date":"7/7/2015","Time":"8:33am","Ask":"6.8988","Bid":"6.8687"},{"id":"USDDKK","Name":"USD/DKK","Rate":"6.7676","Date":"7/7/2015","Time":"8:33am","Ask":"6.7701","Bid":"6.7676"},{"id":"USDEGP","Name":"USD/EGP","Rate":"7.7327","Date":"7/7/2015","Time":"8:33am","Ask":"7.7352","Bid":"7.7327"},{"id":"USDSVC","Name":"USD/SVC","Rate":"8.7395","Date":"7/7/2015","Time":"8:33am","Ask":"8.7445","Bid":"8.7395"},{"id":"USDEEK","Name":"N/A","Rate":"N/A","Date":"N/A","Time":"N/A","Ask":"N/A","Bid":"N/A"},{"id":"USDETB","Name":"USD/ETB","Rate":"20.6850","Date":"7/7/2015","Time":"8:33am","Ask":"20.7880","Bid":"20.6850"},{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9070","Date":"7/7/2015","Time":"8:33am","Ask":"0.9070","Bid":"0.9070"},{"id":"USDHKD","Name":"USD/HKD","Rate":"7.7551","Date":"7/7/2015","Time":"8:33am","Ask":"7.7552","Bid":"7.7551"},{"id":"USDHUF","Name":"USD/HUF","Rate":"286.5400","Date":"7/7/2015","Time":"8:33am","Ask":"286.8600","Bid":"286.5400"},{"id":"USDINR","Name":"USD/INR","Rate":"63.3839","Date":"7/7/2015","Time":"8:33am","Ask":"63.3990","Bid":"63.3839"},{"id":"USDIDR","Name":"USD/IDR","Rate":"13298.0000","Date":"7/7/2015","Time":"8:33am","Ask":"13310.0000","Bid":"13298.0000"},{"id":"USDJPY","Name":"USD/JPY","Rate":"122.6850","Date":"7/7/2015","Time":"8:33am","Ask":"122.7000","Bid":"122.6850"},{"id":"USDKWD","Name":"USD/KWD","Rate":"0.3027","Date":"7/7/2015","Time":"8:33am","Ask":"0.3032","Bid":"0.3027"},{"id":"USDNZD","Name":"USD/NZD","Rate":"1.5032","Date":"7/7/2015","Time":"8:33am","Ask":"1.5035","Bid":"1.5032"},{"id":"USDNOK","Name":"USD/NOK","Rate":"8.1378","Date":"7/7/2015","Time":"8:33am","Ask":"8.1403","Bid":"8.1378"},{"id":"USDPKR","Name":"USD/PKR","Rate":"101.7300","Date":"7/7/2015","Time":"8:33am","Ask":"101.7600","Bid":"101.7300"},{"id":"USDPHP","Name":"USD/PHP","Rate":"45.1575","Date":"7/7/2015","Time":"8:33am","Ask":"45.1680","Bid":"45.1575"},{"id":"USDPLN","Name":"USD/PLN","Rate":"3.8149","Date":"7/7/2015","Time":"8:33am","Ask":"3.8180","Bid":"3.8149"},{"id":"USDRUB","Name":"USD/RUB","Rate":"57.3045","Date":"7/7/2015","Time":"8:33am","Ask":"57.3100","Bid":"57.3045"},{"id":"USDSGD","Name":"USD/SGD","Rate":"1.3539","Date":"7/7/2015","Time":"8:33am","Ask":"1.3540","Bid":"1.3539"},{"id":"USDZAR","Name":"USD/ZAR","Rate":"12.4487","Date":"7/7/2015","Time":"8:33am","Ask":"12.4562","Bid":"12.4487"},{"id":"USDSEK","Name":"USD/SEK","Rate":"8.4844","Date":"7/7/2015","Time":"8:33am","Ask":"8.4852","Bid":"8.4844"},{"id":"USDCHF","Name":"USD/CHF","Rate":"0.9436","Date":"7/7/2015","Time":"8:33am","Ask":"0.9437","Bid":"0.9436"}]}}}
I think you'd be better off creating new rows instead of TD's:
var json = {"query":{"count":29,"created":"2015-07-07T07:33:27Z","lang":"nl-NL","results":{"rate":[{"id":"USDARS","Name":"USD/ARS","Rate":"9.1173","Date":"7/7/2015","Time":"8:33am","Ask":"9.1214","Bid":"9.1173"},{"id":"USDAUD","Name":"USD/AUD","Rate":"1.3374","Date":"7/7/2015","Time":"8:33am","Ask":"1.3376","Bid":"1.3374"},{"id":"USDBHD","Name":"USD/BHD","Rate":"0.3770","Date":"7/7/2015","Time":"8:33am","Ask":"0.3790","Bid":"0.3770"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.1391","Date":"7/7/2015","Time":"8:33am","Ask":"3.1392","Bid":"3.1391"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6428","Date":"7/7/2015","Time":"8:33am","Ask":"0.6428","Bid":"0.6428"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.2098","Date":"7/7/2015","Time":"8:33am","Ask":"6.2104","Bid":"6.2098"},{"id":"USDHRK","Name":"USD/HRK","Rate":"6.8687","Date":"7/7/2015","Time":"8:33am","Ask":"6.8988","Bid":"6.8687"},{"id":"USDDKK","Name":"USD/DKK","Rate":"6.7676","Date":"7/7/2015","Time":"8:33am","Ask":"6.7701","Bid":"6.7676"},{"id":"USDEGP","Name":"USD/EGP","Rate":"7.7327","Date":"7/7/2015","Time":"8:33am","Ask":"7.7352","Bid":"7.7327"},{"id":"USDSVC","Name":"USD/SVC","Rate":"8.7395","Date":"7/7/2015","Time":"8:33am","Ask":"8.7445","Bid":"8.7395"},{"id":"USDEEK","Name":"N/A","Rate":"N/A","Date":"N/A","Time":"N/A","Ask":"N/A","Bid":"N/A"},{"id":"USDETB","Name":"USD/ETB","Rate":"20.6850","Date":"7/7/2015","Time":"8:33am","Ask":"20.7880","Bid":"20.6850"},{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9070","Date":"7/7/2015","Time":"8:33am","Ask":"0.9070","Bid":"0.9070"},{"id":"USDHKD","Name":"USD/HKD","Rate":"7.7551","Date":"7/7/2015","Time":"8:33am","Ask":"7.7552","Bid":"7.7551"},{"id":"USDHUF","Name":"USD/HUF","Rate":"286.5400","Date":"7/7/2015","Time":"8:33am","Ask":"286.8600","Bid":"286.5400"},{"id":"USDINR","Name":"USD/INR","Rate":"63.3839","Date":"7/7/2015","Time":"8:33am","Ask":"63.3990","Bid":"63.3839"},{"id":"USDIDR","Name":"USD/IDR","Rate":"13298.0000","Date":"7/7/2015","Time":"8:33am","Ask":"13310.0000","Bid":"13298.0000"},{"id":"USDJPY","Name":"USD/JPY","Rate":"122.6850","Date":"7/7/2015","Time":"8:33am","Ask":"122.7000","Bid":"122.6850"},{"id":"USDKWD","Name":"USD/KWD","Rate":"0.3027","Date":"7/7/2015","Time":"8:33am","Ask":"0.3032","Bid":"0.3027"},{"id":"USDNZD","Name":"USD/NZD","Rate":"1.5032","Date":"7/7/2015","Time":"8:33am","Ask":"1.5035","Bid":"1.5032"},{"id":"USDNOK","Name":"USD/NOK","Rate":"8.1378","Date":"7/7/2015","Time":"8:33am","Ask":"8.1403","Bid":"8.1378"},{"id":"USDPKR","Name":"USD/PKR","Rate":"101.7300","Date":"7/7/2015","Time":"8:33am","Ask":"101.7600","Bid":"101.7300"},{"id":"USDPHP","Name":"USD/PHP","Rate":"45.1575","Date":"7/7/2015","Time":"8:33am","Ask":"45.1680","Bid":"45.1575"},{"id":"USDPLN","Name":"USD/PLN","Rate":"3.8149","Date":"7/7/2015","Time":"8:33am","Ask":"3.8180","Bid":"3.8149"},{"id":"USDRUB","Name":"USD/RUB","Rate":"57.3045","Date":"7/7/2015","Time":"8:33am","Ask":"57.3100","Bid":"57.3045"},{"id":"USDSGD","Name":"USD/SGD","Rate":"1.3539","Date":"7/7/2015","Time":"8:33am","Ask":"1.3540","Bid":"1.3539"},{"id":"USDZAR","Name":"USD/ZAR","Rate":"12.4487","Date":"7/7/2015","Time":"8:33am","Ask":"12.4562","Bid":"12.4487"},{"id":"USDSEK","Name":"USD/SEK","Rate":"8.4844","Date":"7/7/2015","Time":"8:33am","Ask":"8.4852","Bid":"8.4844"},{"id":"USDCHF","Name":"USD/CHF","Rate":"0.9436","Date":"7/7/2015","Time":"8:33am","Ask":"0.9437","Bid":"0.9436"}]}}};
var count = json.query.count,
created = json.query.created,
lang = json.query.lang;
for(i=0; i<json.query.results.rate.length; i++) {
var row = json.query.results.rate[i]; // Save a reference to the row.
$("<tr>").appendTo($("#result")) // Create new row, append it to the table's html.
.append('<td>' + count + '</td>') // Add all the data to the table.
.append('<td>' + created + '</td>')
.append('<td>' + lang + '</td>')
.append('<td>' + row.id + '</td>')
.append('<td>' + row.Name + '</td>')
.append('<td>' + row.Rate + '</td>')
.append('<td>' + row.Date + '</td>')
.append('<td>' + row.Time + '</td>')
.append('<td>' + row.Ask + '</td>')
.append('<td>' + row.Bid + '</td>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="result">
<tr>
<th>Count:</th>
<th>Created:</th>
<th>Lang:</th>
<th>Id:</th>
<th>Name:</th>
<th>Rate:</th>
<th>Date:</th>
<th>Time:</th>
<th>Ask:</th>
<th>Bid:</th>
</tr>
</table>
(I removed the console.log calls to make the answer a little shorter)
The vanilla js way would be to write a loop that inserts values into your table
Click Run code snippet to see the results
function createTd(text) {
var td = document.createElement('td');
td.textContent = text;
return td;
}
var data = [
{a: 1, b: 2, c: 3},
{a: 4, b: 5, c: 6},
{a: 7, b: 8, c: 9}
];
var table = document.querySelector('table');
data.forEach(function(row) {
var tr = document.createElement('tr');
tr.appendChild(createTd(row.a));
tr.appendChild(createTd(row.b));
tr.appendChild(createTd(row.c));
table.appendChild(tr);
});
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
<tr>
<table>
All that DOM creation is a chore tho, right?
Here's a nice way to do it with React.
Click Run code snippet to see the results
table td {
font-size: 8pt;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
<script type="text/jsx">
var data = JSON.parse('{"query":{"count":29,"created":"2015-07-07T07:36:44Z","lang":"en-US","results":{"rate":[{"id":"USDARS","Name":"USD/ARS","Rate":"9.1187","Date":"7/7/2015","Time":"8:35am","Ask":"9.1228","Bid":"9.1187"},{"id":"USDAUD","Name":"USD/AUD","Rate":"1.3371","Date":"7/7/2015","Time":"8:36am","Ask":"1.3374","Bid":"1.3371"},{"id":"USDBHD","Name":"USD/BHD","Rate":"0.3770","Date":"7/7/2015","Time":"8:35am","Ask":"0.3790","Bid":"0.3770"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.1391","Date":"7/7/2015","Time":"8:35am","Ask":"3.1392","Bid":"3.1391"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6429","Date":"7/7/2015","Time":"8:36am","Ask":"0.6429","Bid":"0.6429"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.2076","Date":"7/7/2015","Time":"8:36am","Ask":"6.2088","Bid":"6.2076"},{"id":"USDHRK","Name":"USD/HRK","Rate":"6.8681","Date":"7/7/2015","Time":"8:36am","Ask":"6.8982","Bid":"6.8681"},{"id":"USDDKK","Name":"USD/DKK","Rate":"6.7667","Date":"7/7/2015","Time":"8:36am","Ask":"6.7671","Bid":"6.7667"},{"id":"USDEGP","Name":"USD/EGP","Rate":"7.8323","Date":"7/7/2015","Time":"8:35am","Ask":"7.8550","Bid":"7.8323"},{"id":"USDSVC","Name":"USD/SVC","Rate":"8.7395","Date":"7/7/2015","Time":"8:35am","Ask":"8.7445","Bid":"8.7395"},{"id":"USDEEK","Name":"N/A","Rate":"N/A","Date":"N/A","Time":"N/A","Ask":"N/A","Bid":"N/A"},{"id":"USDETB","Name":"USD/ETB","Rate":"20.6850","Date":"7/7/2015","Time":"8:35am","Ask":"20.7880","Bid":"20.6850"},{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9069","Date":"7/7/2015","Time":"8:36am","Ask":"0.9070","Bid":"0.9069"},{"id":"USDHKD","Name":"USD/HKD","Rate":"7.7551","Date":"7/7/2015","Time":"8:36am","Ask":"7.7558","Bid":"7.7551"},{"id":"USDHUF","Name":"USD/HUF","Rate":"286.5950","Date":"7/7/2015","Time":"8:36am","Ask":"286.7000","Bid":"286.5950"},{"id":"USDINR","Name":"USD/INR","Rate":"63.3650","Date":"7/7/2015","Time":"8:36am","Ask":"63.3700","Bid":"63.3650"},{"id":"USDIDR","Name":"USD/IDR","Rate":"13305.0000","Date":"7/7/2015","Time":"8:36am","Ask":"13315.0000","Bid":"13305.0000"},{"id":"USDJPY","Name":"USD/JPY","Rate":"122.6800","Date":"7/7/2015","Time":"8:36am","Ask":"122.7000","Bid":"122.6800"},{"id":"USDKWD","Name":"USD/KWD","Rate":"0.3027","Date":"7/7/2015","Time":"8:35am","Ask":"0.3032","Bid":"0.3027"},{"id":"USDNZD","Name":"USD/NZD","Rate":"1.5029","Date":"7/7/2015","Time":"8:36am","Ask":"1.5033","Bid":"1.5029"},{"id":"USDNOK","Name":"USD/NOK","Rate":"8.1454","Date":"7/7/2015","Time":"8:36am","Ask":"8.1473","Bid":"8.1454"},{"id":"USDPKR","Name":"USD/PKR","Rate":"101.7300","Date":"7/7/2015","Time":"8:35am","Ask":"101.7600","Bid":"101.7300"},{"id":"USDPHP","Name":"USD/PHP","Rate":"45.1385","Date":"7/7/2015","Time":"8:35am","Ask":"45.1940","Bid":"45.1385"},{"id":"USDPLN","Name":"USD/PLN","Rate":"3.8152","Date":"7/7/2015","Time":"8:36am","Ask":"3.8156","Bid":"3.8152"},{"id":"USDRUB","Name":"USD/RUB","Rate":"57.3075","Date":"7/7/2015","Time":"8:36am","Ask":"57.3220","Bid":"57.3075"},{"id":"USDSGD","Name":"USD/SGD","Rate":"1.3536","Date":"7/7/2015","Time":"8:36am","Ask":"1.3537","Bid":"1.3536"},{"id":"USDZAR","Name":"USD/ZAR","Rate":"12.4555","Date":"7/7/2015","Time":"8:36am","Ask":"12.4569","Bid":"12.4555"},{"id":"USDSEK","Name":"USD/SEK","Rate":"8.4893","Date":"7/7/2015","Time":"8:36am","Ask":"8.4906","Bid":"8.4893"},{"id":"USDCHF","Name":"USD/CHF","Rate":"0.9435","Date":"7/7/2015","Time":"8:36am","Ask":"0.9436","Bid":"0.9435"}]}}}');
var Table = React.createClass({
renderRow: function(row) {
return (
<tr key={row.id}>
<td>{this.props.data.query.count}</td>
<td>{this.props.data.query.created}</td>
<td>{this.props.data.query.lang}</td>
<td>{row.id}</td>
<td>{row.Name}</td>
<td>{row.Rate}</td>
<td>{row.Date}</td>
<td>{row.Time}</td>
<td>{row.Ask}</td>
<td>{row.Bid}</td>
</tr>
);
},
render: function() {
return (
<table>
<tr>
<td>Count</td>
<td>Created</td>
<td>Lang</td>
<td>Id</td>
<td>Name</td>
<td>Rate</td>
<td>Date</td>
<td>Time</td>
<td>Ask</td>
<td>Bid</td>
</tr>
<tbody>
{this.props.data.query.results.rate.map(this.renderRow, this)}
</tbody>
</table>
)
}
});
React.render(<Table data={data} />, document.body);
</script>
You can do it dynamically by formatting your html like this
<table id='results'></table>
$.each(json.query.results.rate,function(i,item))
{
var table=$('#results'),
newRow = table.append($('<tr/>'));
for(var p in item){
newRow.append('<td>'+normalizeProperty(p)+'</td><td>'+item[p]+'</td>')
}
}
the normalizeProperty function is a function that allows you to convert properties into user-friendly names. Here is an example
function normalizeProperty(p){
p=p||"";
return p.replace('_','').toUppercase();
}

Categories

Resources