I have some HTML table (without tbody tag) where I want to convert the HTML data into key-value pair(header-data) in jQuery array.
When you run code snippet, the output I get is only for last row.
************Actual Output************
[
"Company:Swiggy",
"Contact:Gotya",
"Country:Japan"
]
************Needed Output************
[
"Company:Creamy Cola",
"Contact:Atharva",
"Country:Switzerland"
],
[
"Company:Tuty Fruity",
"Contact:Suyog",
"Country:UK"
],
[
"Company:Milky Way",
"Contact:Santosh",
"Country:US"
],
[
"Company:Swiggy",
"Contact:Gotya",
"Country:Japan"
]
I checked below references too, but couldn't find logic.
Convert HTML Rows into Name Value Pair in JQuery
get values from table as key value pairs with jquery
Thanks in advance for your help.
This is what I have tried so far, please run snippet to get answer in console.
/******JQUERY SCRIPT******/
/*Get Header*/
var xKey = [];
$("#xxx th").each(function() {
var tempColName = $(this).text(); {
xKey.push(tempColName);
}
});
//console.log("Key");
//console.log(xKey);
/*Get Data*/
var xValue = [];
$("#xxx tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() {
arrayOfThisRow.push($(this).text());
});
xValue.push(arrayOfThisRow);
}
});
//console.log("Value");
//console.log(xValue);
//My logic below
var xFinalArr = [];
for (var i = 0; i < xKey.length; i++) {
var su = "";
for (var j = 0; j < xValue.length; j++) {
su = xKey[i] + ":" + xValue[j][i];
}
xFinalArr.push(su);
}
console.log("Output");
console.log(xFinalArr);
/******CSS STYLE******/
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<!--HTML-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<table id="xxx">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Creamy Cola</td>
<td>Atharva</td>
<td>Switzerland</td>
</tr>
<tr>
<td>Tuty Fruity</td>
<td>Suyog</td>
<td>UK</td>
</tr>
<tr>
<td>Milky Way</td>
<td>Santosh</td>
<td>US</td>
</tr>
<tr>
<td>Swiggy</td>
<td>Gotya</td>
<td>Japan</td>
</tr>
</table>
</body>
</html>