Reputation: 2654
I have an ajax function whose response is a html table.I need to convert it into array.
My response is like the following:
<table>
<tr>
<td>4362</td>
<td>Education</td>
</tr>
<tr>
<td>4373</td>
<td>Education world</td>
</tr>
</table>
I need to change this to following array.
[['4362','Education'],['4373','Education world']]
I have done the following ajax code but is not giving me the exact form.
success:function(hasil) {
var table_response = $.parseHTML($(hasil).filter('table').html());
console.log($(table_response).each(function(index, tr) {
$('td', tr).map(function(index, td) {
return $(td).text()
})
}));
}
I have tried another code also,but its giving me all td contents in the array
console.log($('td', table_response).map(function(_, el) {
return $(el).html()
}));
Upvotes: 3
Views: 608
Reputation: 160
function storearrValues()
{
var TableData = new Array();
$('#myDemotable tr').each(function(row, tr){
TableData[row]={
"Id" : $(tr).find('td:eq(0)').text()
, "Value" :$(tr).find('td:eq(1)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
var getData=JSON.stingify(storearrValues())
Upvotes: 0
Reputation: 1369
var result = [];
$("#tbl").find("tr").each(function(index, tr) {
var temp = [];
$(tr).find("td").each(function(index, td) {
temp.push($(td).text());
});
result.push(temp);
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbl"><tr><td>4362</td><td>Education</td></tr>
<tr><td>4373</td><td>Education world</td>
</tr>
</table>
Upvotes: 1
Reputation: 2387
(function (){
var response = `<table><tr><td>4362</td><td>Education</td></tr>
<tr><td>4373</td><td>Education world</td>
</tr>
</table>`;
var arr = [];
$(response).find('tr').each(function(index){
var row = arr[index] = [];
$(this).find('td').each(function(i){
row[i] = $(this).text();
})
})
console.log(arr);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 1674
try this https://jsfiddle.net/492f9y84/1/
var arr=[]
var table_response = $.parseHTML($(hasil).filter('table').html());
$(table_response).find("tr").each(function(index, tr) {
var trArr = []
$(tr).find('td').each(function(index, td) {
trArr.push($(td).text())
})
arr.push(trArr)
});
console.log(arr)
Upvotes: 1