Таблица в JSON + rowspan в массив

Итак, у меня есть таблица с строками Таблица в JSON + rowspan в массив

С текущей функцией у меня есть JSON следующим образом:

[{"value1":"1","value2":"2","value3":"3"},{"value1":"1","value2":"2","value3":"4"},{"value1":"1","value2":"5","value3":"6"},{"value1":"5","value2":"7"},{"value1":"8","value2":"9","value3":"10"},{"value1":"8","value2":"9","value3":"11"},{"value1":"8","value2":"5","value3":"12"},{"value1":"5","value2":"13"}]

Таблица

<table border = "1" id = "example-table">
    <thead>
        <tr>
            <th>col1</th>
            <th>col2</th>
            <th>col3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td rowspan = "4">1</td>
            <td rowspan = "2">2</td>
            <td>3</td>            
        </tr>
        <tr>
            <td>4</td>
        </tr>
        <tr>
            <td rowspan = "2">5</td>
            <td>6</td>
        </tr>
        <tr>
            <td>7</td>
        </tr>
        <tr>
            <td rowspan = "4">8</td>
            <td rowspan = "2">9</td>
            <td>10</td>            
        </tr>
        <tr>
            <td>11</td>
        </tr>
        <tr>
            <td rowspan = "2">5</td>
            <td>12</td>
        </tr>
        <tr>
            <td>13</td>
        </tr>
    </tbody>
</table>
<br>
<button id = "convert-table">Convert</button>
<br>
<textarea id = "res"></textarea>

Функция

(function ($) {
    'use strict'; 
    $.fn.tableToJSON = function (opts) {
        // Set options
        var defaults = {ignoreColumns: [],onlyColumns: null,ignoreHiddenRows: true,headings: null,allowHTML: false};
        opts = $.extend(defaults, opts);
        var notNull = function (value) {return value !== undefined && value !== null;};
        var ignoredColumn = function (index) {
            if (notNull(opts.onlyColumns)) {return $.inArray(index, opts.onlyColumns) === -1;}
            return $.inArray(index, opts.ignoreColumns) !== -1;
        };

        var arraysToHash = function (keys, values) {
            var result = {}, index = 0;
            $.each(values, function (i, value) {
                // when ignoring columns, the header option still starts
                // with the first defined column
                if (index < keys.length && notNull(value)) {
                    result[keys[index]] = value;
                    index++;}});
            return result;
        };
        var cellValues = function (cellIndex, cell) {
            var value, result;
            if (!ignoredColumn(cellIndex)) {
                var override = $(cell).data('override');
                if (opts.allowHTML) {value = $.trim($(cell).html());} 
                else {value = $.trim($(cell).text());}
                result = notNull(override) ? override : value;
            }
            return result;
        };

        var rowValues = function (row) {
            var result = [];
            $(row).children('td,th').each(function (cellIndex, cell) {
                if (!ignoredColumn(cellIndex)) {result.push(cellValues(cellIndex, cell));}
            });
            return result;
        };

        var getHeadings = function (table) {
            var firstRow = table.find('tr:first').first();
            return notNull(opts.headings) ? opts.headings : rowValues(firstRow);
        };

var construct = function (table, headings) {
    var i, j, len, len2, txt, $row, $cell,
    tmpArray = [],cellIndex = 0,result = [];
table.children('tbody,*').children('tr').each(function (rowIndex, row) {
    if (rowIndex > 0 || notNull(opts.headings)) {$row = $(row);
    if ($row.is(':visible') || !opts.ignoreHiddenRows) {
        if (!tmpArray[rowIndex]) {
            tmpArray[rowIndex] = [];}
        cellIndex = 0;
        $row.children().each(function () {
            if (!ignoredColumn(cellIndex)) {$cell = $(this);

            // process rowspans
            if ($cell.filter('[rowspan]').length) {
                len = parseInt($cell.attr('rowspan'), 10) - 1;
                txt = cellValues(cellIndex, $cell, []);
                for (i = 1; i <= len; i++) {
                    if (!tmpArray[rowIndex + i]) {
                        tmpArray[rowIndex + i] = [];
                    }
                    tmpArray[rowIndex + i][cellIndex] = txt;
                }
            }
            // process colspans
            if ($cell.filter('[colspan]').length) {
                len = parseInt($cell.attr('colspan'), 10) - 1;
                txt = cellValues(cellIndex, $cell, []);
                for (i = 1; i <= len; i++) {
                    // cell has both col and row spans
                    if ($cell.filter('[rowspan]').length) {
                        len2 = parseInt($cell.attr('rowspan'), 10);
                        for (j = 0; j < len2; j++) {
                            tmpArray[rowIndex + j][cellIndex + i] = txt;
                        }
                    } else {
                        tmpArray[rowIndex][cellIndex + i] = txt;
                    }
                }
            }
            // skip column if already defined
            while (tmpArray[rowIndex][cellIndex]) {
                cellIndex++;
            }
            if (!ignoredColumn(cellIndex)) {
                txt = tmpArray[rowIndex][cellIndex] || cellValues(cellIndex, $cell, []);
                if (notNull(txt)) {
                    tmpArray[rowIndex][cellIndex] = txt;
                }
            }
            }
            cellIndex++;
        });
    }
    }
});
    $.each(tmpArray, function (i, row) {
        if (notNull(row)) {
            txt = arraysToHash(headings, row);
            result[result.length] = txt;
        }
    });
    return result;
};

// Run
var headings = getHeadings(this);
return construct(this, headings);
    };
})(jQuery);

$('#convert-table').click(function () {
    var table = $('#example-table').tableToJSON(); // Convert the table into a javascript object
    console.info(table);
    var json = JSON.stringify(table);
    var res = document.getElementById("res");
    res.value = json;
});

Как я могу изменить, чтобы получить массив value2 и value3 без дублирования данных и без пустых элементов в нем? Помогите мне, пожалуйста, потому что я не могу найти документацию, которая может помочь мне в этом. Спасибо за ваш вклад

что вы подразумеваете под получить массу value2 и value3

madalinivascu 04.02.2019 10:33

я имею в виду, что в значении1 должно быть 2 элемента значения 2 и в каждом значении2 должно быть 2 элемента значения3

Nick 04.02.2019 11:25

Это совсем не помогло. Пожалуйста, проверьте словарь для синонима

mplungjan 04.02.2019 11:40
Как конвертировать HTML в PDF с помощью jsPDF
Как конвертировать HTML в PDF с помощью jsPDF
В этой статье мы рассмотрим, как конвертировать HTML в PDF с помощью jsPDF. Здесь мы узнаем, как конвертировать HTML в PDF с помощью javascript.
1
3
417
0

Другие вопросы по теме