I used cheerio for the first time today
This is a simplified version of the html source I want.
<div id="country-table">
<!-- div duplicate cause style -->
<div>
<div>
<table>
<tbody>
<tr>
<td>1</td>
<td>USA</td>
<td>1.6</td>
<td>75.8</td>
<td>132,000</td>
</tr>
<tr>
<td>2</td>
<td>INDIA</td>
<td>12123</td>
<td>1322</td>
<td>123213</td>
</tr>
<tr>
<td>3</td>
<td>BRAZIL</td>
<td>3123</td>
<td>213123</td>
<td>134</td>
</tr>
<tr>
<!-- and more... -->
</tbody>
</table>
</div>
</div>
</div>
and i tried to this:
const axios = require("axios").default;
const cheerio = require("cheerio").default;
axios.get("https://coronaboard.kr").then((html) => {
const arr = [];
const $ = cheerio.load(html.data, { xml: true, xmlMode: true });
const data = $("#country-table>div>div>table>tbody").each((index, item) => {
arr.push(item);
});
console.log(arr);
});
I want to put information in td into tr.
ex){number:x,name:USA,confirmed:x,and more...}
If anyone knows how to do it, please answer me!
If you're wanting to extract the data from the table, then this will help. Follow the comments to help you understand how it works.
var $ = cheerio.load(html.data);
// targets the specific table with a selector
var html_table = $('#country-table>div>div>table');
// gets table cell values; loops through all tr rows
var table_data = html_table.find('tr').map(function() {
// gets the cells value for the row; loops through each cell and returns an array of values
var cells = $(this).find('td').map(function() {return $(this).text().trim();}).toArray();
// returns an array of the cell data collected
return [cells];
}).toArray();
// output table data
console.log('table_data', table_data);
Hey im working on a project and i can't seem to get the hang of this. I want to loop through my nested array object "products" so that i can display it all and not just the last index.
// jquery getting our json order data from firebase
$.get("http://localhost:8888/orderslist", (data) => {
// i is for the index of the array of orders
let i = 0;
//for each loop through our array list
$.each(data, function () {
//console.log(data)
//console.log(i);
// is how we arrange the data and show it to the frontpage
$(`<table id = order_table_layout>
<tr>
<th>Customer</th>
<th>Date</th>
<th>Time</th>
<th>Total</th>
<th>Order</th>
<th>Order Status</th>
</tr>
<tr>
<td>${data[i].customer_name}</td>
<td>${data[i].date}</td>
<td>${data[i].time}</td>
<td>${data[i].total} Kr.</td>
<td>
${data[i].products[i].name}
${data[i].products[i].price} Kr.
</td>
<td>
</td>
</tr>
</table>`
).appendTo("#frontpage_new_ordertable");
// counts 1 up for each loop to go through list
i++;
//console.log(i);
});
});
Edit:
An example of the json data I'm working with look like this:
[
{
id: "4WQITi6aXvQJsKilBMns",
customer_name: "Susanne",
date: "22-12-2002",
time: "12:43:19",
total: 222,
products: [
{ name: "product name", price: 100 },
{ name: "product name2", price: 20 }
]
There's a couple of issues in your code. Firstly you're creating a brand new table for every object in the data array. It makes far more sense to instead create a new row in the table for each item.
Also, it appears that you want to loop through the child products array. As such you need an inner loop to create the HTML string for those elements outside of the template literal.
However it's worth noting that it's not good practice to have that much HTML in your JS. A better approach is to have a hidden template tr in your HTML which you can clone, update with the data from the data array, then append to the DOM in the tbody of the table.
With that said, try this:
//$.get("http://localhost:8888/orderslist", (data) => {
// mock response:
let data = [{id:"4WQITi6aXvQJsKilBMns",customer_name:"Susanne",date:"22-12-2002",time:"12:43:19",total:222,products:[{name:"product name",price:100},{name:"product name2",price:20}]},{id:"asjdkjk21ijjjew",customer_name:"Foo Bar",date:"10-05-2020",time:"16:46:16",total:68,products:[{name:"Lorem ipsum",price:50},{name:"Fizz buzz",price:18}]}];
let rows = data.map(item => {
let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
$clone.find('.customer-name').text(item.customer_name);
$clone.find('.date').text(item.date);
$clone.find('.time').text(item.time);
$clone.find('.total').text(item.total + ' Kr.');
let products = item.products.map(prod => `${prod.name}: ${prod.price} Kr.`);
$clone.find('.products').html(products.join('<br />'));
return $clone;
});
$("#frontpage_new_ordertable tbody").append(rows);
//});
tfoot {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="frontpage_new_ordertable">
<tbody>
<tr>
<th>Customer</th>
<th>Date</th>
<th>Time</th>
<th>Total</th>
<th>Order</th>
<th>Order Status</th>
</tr>
</tbody>
<tfoot>
<tr>
<td class="customer-name"></td>
<td class="date"></td>
<td class="time"></td>
<td class="total"></td>
<td class="products"></td>
<td></td>
</tr>
</tfoot>
</table>
<td>${data[i].total} Kr.</td>
<td>
${data[i].products[i].name}
${data[i].products[i].price} Kr.
maybe that's what's wrong?
is the number of the order similar to the number of product in products array?
I trying to learn jquery as im new to it. here I have made a request to this example API and got an array of object that i have to list in to the table. However, im stuck on how to sort in to the table? please help me out
I have my html
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td data-column="ID" id="_id"></td>
<td data-column="Name" id="_name"></td>
<td data-column="Age" id="_age"></td>
<td data-column="Salay" id="_salay"></td>
</tr>
</tbody>
</table>
and my script
$(document).ready(function(){
$("button").click(function(){
$.get("http://dummy.restapiexample.com/api/v1/employees", function(data, status){
if(data.status == "success"){
let listData = JSON.parse(data.data)
console.log(listData);
}
});
});
});
here i got an error as below:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at Function.parse [as parseJSON] ()
$.each(listData,function(key,value){
var trrow='<tr><td data-column="ID" id="_id">'+value["ID"]+'</td><td data-column="Name" id="_name">'+value["Name"]+'</td><td data-column="Age" id="_age">'+value["Age"]+'</td><td data-column="Salay" id="_salay">'+value["Salay"]+'</td>
</tr>';
$("tbody").append(trrow);
});
Basically you are again parsing a JSON array which is return from API.
Your API is returning the below data.
var data={"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""},{"id":"2","employee_name":"Garrett Winters","employee_salary":"170750","employee_age":"63","profile_image":""},{"id":"3","employee_name":"Ashton Cox","employee_salary":"86000","employee_age":"66","profile_image":""},{"id":"4","employee_name":"Cedric Kelly","employee_salary":"433060","employee_age":"22","profile_image":""},{"id":"5","employee_name":"Airi Satou","employee_salary":"162700","employee_age":"33","profile_image":""},{"id":"6","employee_name":"Brielle Williamson","employee_salary":"372000","employee_age":"61","profile_image":""},{"id":"7","employee_name":"Herrod Chandler","employee_salary":"137500","employee_age":"59","profile_image":""},{"id":"8","employee_name":"Rhona Davidson","employee_salary":"327900","employee_age":"55","profile_image":""},{"id":"9","employee_name":"Colleen Hurst","employee_salary":"205500","employee_age":"39","profile_image":""},{"id":"10","employee_name":"Sonya Frost","employee_salary":"103600","employee_age":"23","profile_image":""},{"id":"11","employee_name":"Jena Gaines","employee_salary":"90560","employee_age":"30","profile_image":""},{"id":"12","employee_name":"Quinn Flynn","employee_salary":"342000","employee_age":"22","profile_image":""},{"id":"13","employee_name":"Charde Marshall","employee_salary":"470600","employee_age":"36","profile_image":""},{"id":"14","employee_name":"Haley Kennedy","employee_salary":"313500","employee_age":"43","profile_image":""},{"id":"15","employee_name":"Tatyana Fitzpatrick","employee_salary":"385750","employee_age":"19","profile_image":""},{"id":"16","employee_name":"Michael Silva","employee_salary":"198500","employee_age":"66","profile_image":""},{"id":"17","employee_name":"Paul Byrd","employee_salary":"725000","employee_age":"64","profile_image":""},{"id":"18","employee_name":"Gloria Little","employee_salary":"237500","employee_age":"59","profile_image":""},{"id":"19","employee_name":"Bradley Greer","employee_salary":"132000","employee_age":"41","profile_image":""},{"id":"20","employee_name":"Dai Rios","employee_salary":"217500","employee_age":"35","profile_image":""},{"id":"21","employee_name":"Jenette Caldwell","employee_salary":"345000","employee_age":"30","profile_image":""},{"id":"22","employee_name":"Yuri Berry","employee_salary":"675000","employee_age":"40","profile_image":""},{"id":"23","employee_name":"Caesar Vance","employee_salary":"106450","employee_age":"21","profile_image":""},{"id":"24","employee_name":"Doris Wilder","employee_salary":"85600","employee_age":"23","profile_image":""}]};
let listData = JSON.parse(data.data) // replace this line
let listData=data.data;// its already JSON Array
for Example
var a=[{name:"John"},{name:"DOE"}]
JSON.parse(a) // it will give you same error which is mentioned in a question.
I currently have a jQuery script that matches the values from my table to an array to find a corresponding url and output it as html. It works fine however I would like to keep my array private (so that all of the data cannot be viewed in the inspector if a match isn't found) and from my understanding that cannot be done with javascript. I am already using PHP to dynamically create the table so I was wondering whether this would be possible.
var profiles = [{
"name": "Susie",
"link": "www.google.com"
},
{
"name": "John",
"link": "www.yahoo.com"
}
];
$(document).ready(function() {
$('tr').each(function(index, item) {
var value = $(item).find('td').eq(1).text();
var exist = profiles.filter(c => c.name == value);
if (exist.length > 0) {
var link = exist[0].link;
$(item).find('td').eq(1).html("<a href='" + link + "'>" + value + "</a>");
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<th>#</th>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>1
<td>Susie</td>
</tr>
<tr>
<td>2
<td>John</td>
</tr>
</tbody>
I was thinking of using a JSON file to store the data but I am not sure where to go from there.
$data = '{"Susie": "www.google.com","John": "www.yahoo.com"}';
$array = json_decode($somedata, TRUE);
I have a table and I need to get values for each row (in array), something like:
[{1,'test'}, {2,'another test'}, {3, 'nothing'}], but the only I can get is:
["1 test", "2 another test","3 nothing"]. I need to send this values by ajax as json object ... and create another table - thus I need an array of values ...
var table = $("table");
var rowsAll = table.find("tbody tr");
rowsAll.each(function(i,l) {
var rows = [];
$(this).each(function(t,l){
rows[rows.length] = cells[t]= $(this).text();
return rows; //returns rows, but I need cells of each row
}).serialize();//or get()
});
the html is something like this:
<table id="deal">
<thead>
<tr>
<th> num </th>
<th> string </th>
</tr>
</thead>
<tbody>
<tr> <td> 1 </td> <td> test </td> </tr>
<tr> <td> 2 </td> <td> another test </td> </tr>
<tr> <td> 3 </td> <td> nothing </td> </tr>
</tbody>
</table>
I really need help ...
This form of data makes no sense as it's very hard to read with javascript:
[{1,'test'}, {2,'another test'}, {3, 'nothing'}]
I'm going to assume that what you want is this:
{"1": "test", "2": "another test", "3": "nothing"}
To get that second form, you could use this code:
var results = {};
$("#deal tbody tr").each(function() {
var cols = $(this).find("td");
results[$.trim(cols.eq(0).text())] = $.trim(cols.eq(1).text());
});
Working example here: http://jsfiddle.net/jfriend00/WjgrC/.