简体   繁体   中英

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").each(function(rowIndex) {
    $j(this).find("td").each(function(cellIndex) {
        if (cellIndexMapping[cellIndex])
            data.push($j(this).text()  );
    });
});

var fullCSV = data.join(", ");
console.log (fullCSV);

This gives me all of my table elements in a comma separated array. So for example if my table is

<th>| zero | one | two | three | four | five | </th>
---------------------------------------------
<tr>|  A   |  B  |  C  |  D    |  E   |  F   | </tr>
---------------------------------------------
<tr>|  G   |  H  |  I  |  J    |  K   |  L   | </tr>

I get back :

A,B,D,E,F,G,H,J,K,L

What I need to have is a newline "\\n" between each row. So my desired result would look like :

A,B,D,E,F,\n G,H,J,K,L \n

Any ideas?

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) {
    var data = [];
    $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/

You just need to add it at the end of the outer loop:

var res = "";
$j("#myTable tr").each(function(rowIndex) {
    var data = [];
    $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.

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() [docs] :

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM