Creating String From Table With .each, How To Add A Newline After Each Row?
I am grabbing the data out of selected cells of a table with this javascript: var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true}; var data = []; $j('#myTable tr').
Solution 1:
var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true},
data = [],
finalData = [];
$j("#myTable tr").each(function(rowIndex) {
data.push([]);
$j(this).find("td").each(function(cellIndex) {
if (cellIndexMapping[cellIndex])
data[rowIndex].push( $j(this).text() );
});
});
$j.each(data, function(i, e) {
finalData.push( e.join(',') );
});
finalData.join("\n");
Alternatively, you could just append \n
in every loop:
var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true},
finalData = '';
$j("#myTable tr").each(function(rowIndex) {
vardata = [];
$j(this).find("td").each(function(cellIndex) {
if (cellIndexMapping[cellIndex])
data.push( $j(this).text() );
});
finalData += data.join(', ') + "\n";
});
See this fiddle: http://jsfiddle.net/kLsW5/
Solution 2:
You just need to add it at the end of the outer loop:
var res = "";
$j("#myTable tr").each(function(rowIndex) {
vardata = [];
$j(this).find("td").each(function(cellIndex) {
if (cellIndexMapping[cellIndex])
data.push($j(this).text() );
});
res += data.join(", ") + "\n";
});
Now res
holds the final value.
Solution 3:
Are you sure you want the trailing comma in the first line? Don't you want something like:
A,B,D,E,F\nG,H,J,K,L\n
Here is a way using .map()
:
var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true};
var fullCSV = $j("#myTable tr").map(function() {
return $j(this).find("td").map(function(cellIndex) {
return cellIndexMapping[cellIndex] ? $j(this).text() : null;
}).get().join(', ');
}).get().join('\n');
Post a Comment for "Creating String From Table With .each, How To Add A Newline After Each Row?"