使用Javascript将此表解析为对象数组
我有以下源表数据: 我希望得到如下解析的数据(按行分组): 我将源表分组到一个对象数组中。 这是我的阵列:使用Javascript将此表解析为对象数组,javascript,jquery,arrays,object,html-table,Javascript,Jquery,Arrays,Object,Html Table,我有以下源表数据: 我希望得到如下解析的数据(按行分组): 我将源表分组到一个对象数组中。 这是我的阵列: [ { rowId: 4, colId: 10 } { rowId: 4, colId: 11 } .... ] 现在我想得到一个解析对象数组 我该怎么做? 我用for循环解析了数组,但在创建新的对象数组时出现了一些错误 我的代码: for (var i=0; i<tableArray.length; i++) { if (tableArray[i].rowI
[ { 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;
}
for(var i=0;i您可以对元素进行分组,并使用对象作为最后的值。此解决方案需要排序数据
var数组=[{rowId:4,colId:10},{rowId:4,colId:11},{rowId:4,colId:20},{rowId:4,colId:21},{rowId:6,colId:6,{rowId:6,colId:7},{rowId:6,colId:8},{rowId:7,colId:12},],
组=[];
forEach(函数(a,i){
如果(!i | |//如果第一个对象i=0,则组会更改
this.last.row!==a.rowId | |//或不同的rowId
this.last.end+1!==a.colId//或不按顺序
) {
this.last={row:a.rowId,start:a.colId,end:a.colId};
组。推(这个。最后一个);
}
this.last.end=a.colId;
}, {});
console.log(group);
我宁愿编写一个函数来生成新数组,我希望这些注释能够解释它背后的思想过程:
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;
}
函数变换(数组){
var输出=[];
//启动输出数组中所需的第一个对象
//使用输入数组中第一个对象的行和colId
var obj={
行:数组[0]。行,
开始:数组[0]。colId,
结束:数组[0]。colId
};
//循环从1开始,而不是从0开始,因为我们已经使用了第一个对象数组[0]
对于(变量i=1;i
请发布你的js代码问题不清楚如果我理解正确,你想这样做:[{rowId:4,colId:10}{rowId:4,colId:11}….]=>[{rowId:4,start:10,end:12}],对吗?发布js代码。请查看@user2415266结果。这是我想要的。