Is there a JavaScript data table component that displays columns as rows?

I want to display an "inverted" (transposed) data table. For instance. given some data:

[{col1: "abc", col2: 123}, {col1: "xxx", col2: 321}]

It is displayed as

+------+-----+-----+
| col1 | abc | xxx |
+------+-----+-----+
| col2 | 123 | 321 |
+------+-----+-----+

Rows should act like columns in a standard table.

Is there any JS Ajax component (e.g. YUI DataTable or similar)?

+3
source share
1 answer

Good exercise. I think this is what you want:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Transposed table</title>
</head>
<body>
  <div id="wrapper"></div>
  <script>
    var tableData = [{col1: "abc", col2: 123},
                     {col1: "xxx", col2: 321}];

    function rotateData(theTable) {
        var result = [], i, j, key, keyFound;

        for (i = 0; i < theTable.length; ++i) {
            for (key in theTable[i]) {
                /* now loop through result[] to see if key already exists */
                keyFound = false;

                for (j = 0; j < result.length; ++j) {
                    if (result[j][0] == key) {
                        keyFound = true;
                        break;
                    }
                }

                if (!keyFound) {
                    result.push([]);  // add new empty array
                    result[j].push(key);  // add first item (key)
                }

                result[j].push(theTable[i][key]);
            }
        }

        return result;
    }

    function buildTable(theArray) {
        var html = [], n = 0, i, j;

        html[n++] = '<table>';

        for (i = 0; i < theArray.length; ++i) {
            html[n++] = '<tr>';
            for (j = 0; j < theArray[i].length; ++j) {
               html[n++] = '<td>';
               html[n++] = theArray[i][j];
               html[n++] = '</td>';
            }
            html[n++] = '</tr>';
        }

        html[n++] = '</table>';
        return html.join('');
    }

    var rotated = rotateData(tableData);
    var tableHtml = buildTable(rotated);
    document.getElementById('wrapper').innerHTML = tableHtml;
  </script>
</body>
</html>

The function rotateDatarotates the elements of objects inside the array, so that you get an array of type

[["col1", "abc", "xxx"], ["col2", 123, 321]]

, ( ), , "" "" .

buildTable HTML-, , . BTW, html , . , () .

+2

Source: https://habr.com/ru/post/1759483/


All Articles