使用Javascript将此表解析为对象数组

时间:2016-05-31 15:08:07

标签: javascript jquery arrays object html-table

我有这个源表数据:

Table source data

我希望像这样解析数据(按行分组):

Table destination data

我将源表分组为一个对象数组。 这是我的阵列:

[ { rowId: 4, colId: 10 } { rowId: 4, colId: 11 } .... ]

现在我想获得一组已解析的对象..

我该怎么做? 我用for循环解析了数组但是在创建新的对象数组时出现了一些错误。

我的代码:

    for (var i=0; i<tableArray.length; i++) {

    if (tableArray[i].rowId != rowLast) {
        bar = true;     
        var row = tableArray[i].rowId;
        var start = tableArray[i].colId;
    }

    if  ((bar)&&(tableArray[i].colId != colLast)) {
        var end = tableArray[i].colId;
        tab = { row: row, start: start, end: end }
        newTableArray.push(tab);
        bar = false;
    }


    rowLast = tableArray[i].rowId;
    colLast = tableArray[i].colId;      

}

帮助!我在循环中有点困惑:(

非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以对元素进行分组,并使用对象作为最后的值。该解决方案需要排序数据。

&#13;
&#13;
var array = [{ rowId: 4, colId: 10 }, { rowId: 4, colId: 11 }, { rowId: 4, colId: 12 }, { rowId: 4, colId: 20 }, { rowId: 4, colId: 21 }, { rowId: 6, colId: 6 }, { rowId: 6, colId: 7 }, { rowId: 6, colId: 8 }, { rowId: 7, colId: 12 }, ],
    group = [];

array.forEach(function (a, i) {
    if (!i ||                          // group changes if first object i = 0
        this.last.row !== a.rowId ||   //               or different rowId
        this.last.end + 1 !== a.colId  //               or not in sequence
    ) {
        this.last = { row: a.rowId, start: a.colId, end: a.colId };
        group.push(this.last);
    }
    this.last.end = a.colId;
}, {});

console.log(group);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我宁愿编写一个函数来生成新数组,我希望这些注释能够解释它背后的思考过程:

function transform(array) {
    var output = [];
    // initiates the first object you want in your output array
    // with the row and colId of the first object from the input array
    var obj = {
        row: array[0].row,
        start: array[0].colId,
        end: array[0].colId
    };
    // Loop starts at 1 instead of 0 because we used the first object array[0] already
    for (var i = 1; i < array.length; i++) {
        var current = array[i];
        // if the current objects row is still the same,
        // AND the colId is the next colId (meaning no spare cols between)
        // set the new objects end to this colId
        if(obj.row === current.row && (current.colId - obj.end) === 1 ){
            obj.end = current.colId;
        }
        // when the row does not match, add the object to the output array and
        // re-innitiate it with the current objects row and colId
        else {
            output.push(obj);
            obj.row = current.row;
            obj.start = current.colId;
            obj.end = current.colId;
        }
    }
    // Once the loop is done, add the last remaining object to the output array
    output.push(obj);
    return output;
}