如何使用javascript [duplicate]从html表动态创建json文件

时间:2021-01-29 01:28:13

This question already has an answer here:

这个问题在这里已有答案:

EDIT: Apologies for the partially duplicate question. I seem to have missed it.

编辑:为部分重复的问题道歉。我似乎错过了它。

I've written a function to scan a table I'd like it to use the header as a property name and add it to an empty object. The problem seems to be with the json object. I have tried all manner of syntax that I have been able to find and haven't been able to add properties to the object.

我编写了一个函数来扫描我想要的表,将标题用作属性名称并将其添加到空对象中。问题似乎与json对象有关。我已经尝试了所有我能够找到并且无法向对象添加属性的语法。

var jsonData = [{}];

function saveTableToDataSet(tableName,jsonObj) {
	debugger;
	var oTable = document.getElementById(tableName);
    var columnNames = []
	var rowLength = oTable.rows.length;
    //get column names
    var oCells = oTable.rows.item(0).cells;
    var cellLength = oCells.length;
    for (var i = 0; i < cellLength; i++) {
        var cellVal = oCells.item(i).innerHTML;
        columnNames[i] = cellVal;
    }
    //get column data
	for (var j = 1; j < rowLength; j++) {
		var oCells = oTable.rows.item(j).cells;
        var cellLength = oCells.length;
        for (var k = 0; k < cellLength; k++) {
            var columnName = columnNames[k];
			var cellVal = oCells.item(k).innerHTML;

   //the problem
			jsonObj[j.columnName] = cellVal;
			}
		}
	}
};

I'm obviously not referencing the object or its properties correctly but I have tried infinite combinations of syntax. All except the correct one seemingly.

我显然没有正确引用对象或其属性,但我尝试了无限的语法组合。除了看似正确的一个以外的所有。

EDIT: It's just seeing my jsonObj parameter as a string. I've changed the last bit to:

编辑:它只是将我的jsonObj参数视为一个字符串。我把最后一点改为:

  //the problem 
  newObj = []; 
  newObj[columnName] = cellVal; 
  jsonData["dataItem"+j] = newObj; 
}

And it's working. Ideally though I'd like to be able to pass the name of the object in.

它正在发挥作用。理想情况下,我希望能够传递对象的名称。

1 个解决方案

#1


0  

Change your call to this:

将您的电话改为:

OnClientClick="saveTableToDataSet('seriesData', jsonData);"

Removing the single quotes will treat jsonData as a variable instead of a literal.

删除单引号会将jsonData视为变量而不是文字。

#1


0  

Change your call to this:

将您的电话改为:

OnClientClick="saveTableToDataSet('seriesData', jsonData);"

Removing the single quotes will treat jsonData as a variable instead of a literal.

删除单引号会将jsonData视为变量而不是文字。