0

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.

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:

  //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.

4
  • How do you call this function? Is the jsonData what is passed to it? Commented Nov 10, 2015 at 15:25
  • At the moment its OnCientClick and I pass the table name and json object name in as arguments: OnClientClick="saveTableToDataSet('seriesData','jsonData');" Commented Nov 10, 2015 at 15:26
  • The reason it sees your jsonObj as a string is because you pass the variable in with quotes around it Commented Nov 10, 2015 at 16:02
  • Wow I feel dumb right now! Thanks. New to js, json and chartsjs so overthinking everything today! Commented Nov 10, 2015 at 16:24

1 Answer 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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.