How to loop over js object and populate values in the table? - javascript

I have js object that looks like this:
{
"id": 9,
"user_name": "John Kim",
"age": 25,
"is_elig": true
}
I have table where data should be populated, looks like this:
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Eligible</th>
</tr>
<tr>
<td id="id"></td>
<td id="user_name"></td>
<td id="age"></td>
<td id="is_elig"></td>
</tr>
</table>
I use JQuery in my project and I was wondering if there is a way to loop over js object and check if the key exist in table td cell id. If does exist then populate the value in the cell.

You could iterate the object:
var obj = {
"id": 9,
"user_name": "John Kim",
"age": 25,
"is_elig": true
}
$.each(obj, function (key, value) {
$("#" + key).text(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Eligible</th>
</tr>
<tr>
<td id="id"></td>
<td id="user_name"></td>
<td id="age"></td>
<td id="is_elig"></td>
</tr>
</table>
Without jQuery, it would not be a lot more difficult:
var obj = {
"id": 9,
"user_name": "John Kim",
"age": 25,
"is_elig": true
}
Object.entries(obj).forEach(([key, value]) =>
document.getElementById(key).textContent = value
);
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Eligible</th>
</tr>
<tr>
<td id="id"></td>
<td id="user_name"></td>
<td id="age"></td>
<td id="is_elig"></td>
</tr>
</table>

Iterate through your object:
let obj = {
"id": 9,
"user_name": "John Kim",
"age": 25,
"is_elig": true
}
Object.keys(obj).forEach(i => $('td#'+ i).text(obj[i]) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Eligible</th>
</tr>
<tr>
<td id="id"></td>
<td id="user_name"></td>
<td id="age"></td>
<td id="is_elig"></td>
</tr>
</table>

I think when you say "loop over js object" you mean "loop over js array of objects". In that case you might do something like this:
<table>
<tr id="tr_users">
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Eligible</th>
</tr>
<div id="tr_users"></div>
</table>
In your js file:
var users = [];
var data = [ALL USERS IN ARRAY];
function setTable(data ) {
data .forEach(u => {
if(userIsNewInTable(u)) {
users.push(u);
}
});
users.forEach(u => {
appendInTable(u);
});
}
function userIsNewInTable(user) {
return !users.includes(user);
}
function appendInTable(value) {
let htmlToInsert = "";
htmlToInsert = `<tr>
<td>${id}</td>
<td>${user_name}</td>
<td>${age}</td>
<td>${is_elig}</td>
</tr>`;
$('#tr_users').append(htmlToInsert);
}
In this approach, we are declaring an empty array that will be fullfilled with the users. We have a function "setTable" that will receive the array of all the data (data). It will iterate over them and check if they already are in the users array to avoid duplicated.
Once we finished the iteration, we can insert the html with all the "td".
Please let me know if that's what you were looking for.
I wish it helped you.
Goodbye!

Related

Javascript grab the data from the table in the HTML and build an array of objects that contains the table data

I have an HTML table and I need to define a function that should grab the data from the table and build an array of objects that contains table data. Outside the function I have to declare a variable and assign the returned value from the function.
Thanks in advance.
HTML
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
JS
function buildTableData() {
let tbody = document.getElementsByTagName("tbody")[0];
let rows = tbody.children;
let people = [];
for (let row of rows) {
let person = {};
let cells = row.children;
person.rating = cells[0].textContent;
person.review = cells[1].textContent;
person.favoriteFood = cells[2].textContent;
people.push(person);
return people;
}
let data = people;
console.log(data);
}
You can get all the elements by using querySelectorAll('td'). Then use map to to get only the text of it and return this.
function buildTableData() {
const elements = [...document.querySelectorAll('td')];
return elements.map(x => {
return {content : x.innerHTML}
});
}
console.log(buildTableData());
<body>
<h2>Product reviews</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/7.3.1/acorn.js" integrity="sha512-4GRq4mhgV43mQBgKMBRG9GbneAGisNSqz6DSgiBYsYRTjq2ggGt29Dk5thHHJu38Er7wByX/EZoG+0OcxI5upg==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn-walk/7.2.0/walk.js" integrity="sha512-j5XDYQOKluxz1i4c7YMMXvjLLw38YFu12kKGYlr2+w/XZLV5Vg2R/VUbhN//K/V6LPKuoOA4pfcPXB5NgV7Gwg==" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
You can try using querySelectorAll() and map() like the following way:
function buildTableData() {
let rows = document.querySelectorAll('tbody tr');
let data = Array.from(rows).map(function(tr){
return {
rating: tr.querySelectorAll('td:nth-child(1)')[0].textContent,
review: tr.querySelectorAll('td:nth-child(2)')[0].textContent,
favoriteFood: tr.querySelectorAll('td:nth-child(3)')[0].textContent
};
});
console.log(data);
}
buildTableData();
<h2>Product reviews</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
You want a loop, and each review to be an object that is appended to an array of reviews is what I'm assuming
var reviews = [];
var tbody = document.querySelectorAll("tbody")[0];
var TRs = tbody.querySelectorAll("tr");
for (var a = 0; a < TRs.length; a++) {
var TDs = TRs[a].querySelectorAll("td");
var review = {
name: "",
rating: "",
review: ""
};
//These assume the order of your table columns don't change
review.name = TDs[0].innerHTML;
review.rating = TDs[1].innerHTML;
review.review = TDs[2].innerHTML;
reviews.push(review);
}
Your reviews array should have everything in there just as you wanted. I assumed the third column was "review" instead of "favorite food"

How can I re-render a view after deleting an object from an array, in Svelte?

I am working on a small Svelte application, for learning purposes (Im new to Svelte). The application uses an array of objects displayed in a view as an HTML table:
let countries = [
{ code: "AF", name: "Afghanistan" },
{ code: "AL", name: "Albania" },
{ code: "IL", name: "Israel" }
];
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Code</th>
<th>Name</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
{#if countries.length}
{#each countries as c, index}
<tr>
<td>{index+1}</td>
<td>{c.code}</td>
<td>{c.name}</td>
<td class="text-right">
<button data-code="{c.code}" on:click="{deleteCountry}" class="btn btn-sm btn-danger">Delete</button>
</td>
</tr>
{/each}
{:else}
<tr>
<td colspan="4">There are no countries</td>
</tr>
{/if}
</tbody>
</table>
I am doing a delete operation this way:
function deleteCountry(){
let ccode = this.getAttribute('data-code');
let itemIdx = countries.findIndex(x => x.code == ccode);
countries.splice(itemIdx,1);
console.log(countries);
}
There is a REPL here.
The problem
I have been unable to render the table (view) again, after the countries array is updated (an element is deleted from it).
How do I do that?
add
countries = countries;
after this line
countries.splice(itemIdx,1);
since reactivity/rerendering/UI update only marked after assignment.
For svelte to pick up the change to your array of countries, you need to create a new reference of the array. For this you could use the Array.filter method.
<script>
let countries = [
{ code: "AF", name: "Afghanistan" },
{ code: "AL", name: "Albania" },
{ code: "IL", name: "Israel" }
];
function deleteCountry(code) {
countries = countries.filter(c => c.code !== code)
}
</script>
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Code</th>
<th>Name</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
{#if countries.length}
{#each countries as c, index}
<tr>
<td>{index+1}</td>
<td>{c.code}</td>
<td>{c.name}</td>
<td class="text-right">
<button on:click="{() => deleteCountry(c.code)}" class="btn btn-sm btn-danger">Delete</button>
</td>
</tr>
{/each}
{:else}
<tr>
<td colspan="4">There are no countries</td>
</tr>
{/if}
</tbody>
</table>
Also you can directly use the country code as an argument for the deleteCountry method.

Get value of only that style attribute who have font family

Html Code:
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td style="font-family:Helvetica,Arial,sans-serif;font-size:13px;">Jill</td>
<td>Smith</td>
<td style="font-family:Helvetica,Arial,sans-serif;font-size:13px;">50</td>
</tr>
<tr>
<td style="font-family:Helvetica,Arial,sans-serif;font-size:13px;">Eve</td>
<td>Jackson</td>
<td style="font-family:Helvetica,Arial,sans-serif;font-size:13px; color:#666; font-weight:bold;
text-decoration:none;margin:0;padding:0;text-align:left;white-space:nowrap;">94</td>
</tr>
</table>
Javascript Code:
<script>
var tg_name = document.getElementsByTagName("td");
var l_tgname = tg_name.length;
array_get = [];
for(h=0;h<=l_tgname;h++){
var val_gt_chck = document.getElementsByTagName("td")[h].hasAttribute("style");
if(val_gt_chck){
var val_gt = document.getElementsByTagName("td")[h].getAttribute("style");
if(val_gt!==null && val_gt !== ''){
check_words = val_gt.includes('font-family');
if(check_words){
alert(val_gt);
array_get.push(val_gt);
}
}
}
}
alert(array_get);
</script>
I wanted to combine all the data in one variable and access that variable outside the loop.It give the error that "Cannot read property 'has Attribute' of undefined"
There was wrong for condition and includes replaced by indexOf for better compatibility:
var tg_name = document.getElementsByTagName("td");
var l_tgname = tg_name.length;
array_get = [];
for(h=0;h<l_tgname;h++){
var val_gt_chck = document.getElementsByTagName("td")[h].hasAttribute("style");
if(val_gt_chck){
var val_gt = document.getElementsByTagName("td")[h].getAttribute("style");
if(val_gt!==null && val_gt !== ''){
check_words = val_gt.indexOf('font-family:') > -1;
if(check_words){
console.log(val_gt);
array_get.push(val_gt);
}
}
}
}
console.log(array_get);
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td style="font-family:Helvetica,Arial,sans-serif;font-size:13px;">Jill</td>
<td>Smith</td>
<td style="font-family:Helvetica,Arial,sans-serif;font-size:13px;">50</td>
</tr>
<tr>
<td style="font-family:Helvetica,Arial,sans-serif;font-size:13px;">Eve</td>
<td>Jackson</td>
<td style="font-family:Helvetica,Arial,sans-serif;font-size:13px; color:#666; font-weight:bold;
text-decoration:none;margin:0;padding:0;text-align:left;white-space:nowrap;">94</td>
</tr>
</table>

How to iterate through each data in a table

<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
I am a bit confused about how to get all the data from the table using a single button. When the user click on the button i should get all the table data. I tried with the below code. I need to get all the data in a array format. So that i can save all the data to my database.
$("#saveButton").click(function(event) {
var table = document.getElementById("table");
var dataArray = [];
var data = table.find('td');
for (var i = 0; i <= data.size() - 1; i = i + 4) {
data.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}
});
Try this code.
$("#saveButton").click(function(event) {
var data = [];
$("#table tr").each(function(i){
if(i != 0){
data.push({
id: $(this).find("td:eq(0)").html(),
name: $(this).find("td:eq(1)").html(),
email: $(this).find("td:eq(2)").html(),
phone: $(this).find("td:eq(3)")}).html()
});
}
});
//do something with data
});
If you want to use jquery, have a look at https://jsfiddle.net/qg6xpy39/
HTML:
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
<button id="saveButton">
click
</button>
JS:
$("#saveButton").click(function(event) {
var rows = $('#table td'); // retrieve the rows of your table
var dataArray = [];
$.each(rows, function(idx, elt) {
dataArray.push($(elt).text()); // add cell text content to the data array
});
console.log(dataArray); // so you can check what's in the array ;-)
});
As said in comments, in plain JavaScirpt.
use querySelectorAll to select all trs. Then iterate in each of them and get it's td's innerHTML and push it in an array.
Then use Array.shift() to remove the th elements. That is, the titles.
The code
function save(){
var arr=[];
var tr=document.querySelectorAll('tr');
tr.forEach(function(x,y){
arr[y]=[];
x.querySelectorAll("td").forEach(function(z){
arr[y].push(z.innerHTML);
});
});
arr.shift();
console.log(arr);
}
Check the below snippet.
function save(){
var arr=[];
var tr=document.querySelectorAll('tr');
tr.forEach(function(x,y){
arr[y]=[];
x.querySelectorAll("td").forEach(function(z){
arr[y].push(z.innerHTML);
});
});
arr.shift();
console.log(arr);
}
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
<button onclick="save();">Save</button>
Another possible approach, again using pure javascript rather than jQuery would be to use the DOM NodeIterator in conjunction with an XPath via Document.evaluate()
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Javascript DOM Processing</title>
<script type='text/javascript'>
document.addEventListener('DOMContentLoaded',function(e){
var query='/html/body/table[#id="table"]/tbody/tr/td';
var xpr = document.evaluate( query, document, null, XPathResult.ANY_TYPE, null );
var td = xpr.iterateNext();
var dataTbl=[];
while( td ){
try{
dataTbl.push( td.textContent );
td=xpr.iterateNext();
}catch( err ){
alert( 'Error'+err );
}
}
/* The data from all table cells is now in the array */
alert( dataTbl.join(String.fromCharCode(10)) );
},false);
</script>
</head>
<body>
<!-- content -->
<table class="table_style" id="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr >
<td>1</td>
<td>ACDB</td>
<td>agaeg#aegrg.com</td>
<td>98900000</td>
</tr>
<tr>
<td>2</td>
<td>DEFG</td>
<td>defg#defg.com</td>
<td>11111112</td>
</tr>
<tr>
<td>3</td>
<td>IJKL</td>
<td>ijkl#ijkl.com</td>
<td>1234323432</td>
</tr>
</tbody>
</table>
</body>
</html>
Simplest approach would be
var data_arr = [];
$('#table tr').each(function() {
data_arr.push(this.cells[0].innerHTML);
data_arr.push(this.cells[1].innerHTML);
data_arr.push(this.cells[2].innerHTML);
data_arr.push(this.cells[3].innerHTML);
});

HTML Table onClick function to get table row key and value

I wanted to create a HTML table with onclick function to get the key and value of a row, so far the onclick function is working but it displaying and empty array for me, how can I fix this problem. Thanks.
I wanted it to be display in console log in this format when you click on the first row:
{ "name":"Clark", "age":29};
Here is my code
var table = document.getElementById("tableID");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
tableText(this);
};
}
}
function tableText(tableRow) {
var myJSON = JSON.stringify(tableRow);
console.log(myJSON);
}
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<tr>
<th hidden="hidden"></th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td >Clark</td>
<td>29</td>
</tr>
<tr>
<td >Bruce</td>
<td>30</td>
</tr>
</tbody>
</table>
I edited my answer to return the data as an object. Run the script and have a look.
var table = document.getElementById("tableID");
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
tableText(this);
};
}
}
function tableText(tableRow) {
var name = tableRow.childNodes[1].innerHTML;
var age = tableRow.childNodes[3].innerHTML;
var obj = {'name': name, 'age': age};
console.log(obj);
}
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<thead>
<tr>
<th hidden="hidden"></th>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td >Clark</td>
<td>29</td>
</tr>
<tr>
<td >Bruce</td>
<td>30</td>
</tr>
</tbody>
</table>
I think you can use tr.innerTestto get the value in the tags
If you are using jQuery you can add an eventlistener to the table like this
$('#tableID').on('click', 'tr', function(e){
tableText($(this).html());
});
function tableText(tableRow) {
var myJSON = JSON.stringify(tableRow);
console.log(myJSON);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table align="center" id="tableID" border="1" style="cursor: pointer;">
<tr>
<td>Text</td>
<td>MoreText</td>
<td>Lorem</td>
<td>Ipsum</td>
</tr>
<tr>
<td>Text</td>
<td>MoreText</td>
<td>Lorem</td>
<td>Ipsum</td>
</tr>
<tr>
<td>Text</td>
<td>MoreText</td>
<td>Lorem</td>
<td>Ipsum</td>
</tr>
<tr>
<td>Text</td>
<td>MoreText</td>
<td>Lorem</td>
<td>Ipsum</td>
</tr>
</table>
There are many ways to do what you're after, however a robust and extensible way would be to get the property names from the table header row, then get the values from the row that was clicked on.
I don't know why you have hidden cells in the header, it just complicates things. If you're using it for data, that would be much better in an associated object or data-* property of the table or row.
function getRowDetails(event) {
row = this;
var table = row.parentNode.parentNode;
var header = table.rows[0];
// Get property names from header cells
var props = [].reduce.call(header.cells, function(acc, cell ) {
if (!cell.hasAttribute('hidden')) {
acc.push(cell.textContent);
}
return acc;
}, []);
// Get value for each prop from data cell clicked on
var result = props.reduce(function(acc, prop, i) {
acc[prop] = row.cells[i].textContent;
return acc;
}, {});
// Do something with result
console.log(result);
return result;
}
// Add listener to body rows, could also put single listener on table
// and use event.target to find row
window.onload = function() {
[].forEach.call(document.getElementsByTagName('tr'), function(row, i) {
if (i) row.addEventListener('click', getRowDetails, false);
});
}
<table align="center" id="tableID" border="1">
<thead>
<tr><th hidden="hidden"></th><th>name</th><th>age</th></tr>
</thead>
<tbody style="cursor: pointer;">
<tr><td >Clark</td><td>29</td></tr>
<tr><td >Bruce</td><td>30</td></tr>
</tbody>
</table>

Categories

Resources