I'm trying to figure out an issue I'm having with JSON and looping through sub objects. I haven't ever used JSON before so please let me know if syntax errors are causing my issues.
I have this JSON object defined:
var columnData = {
"obj1":{Heading: "Test 1", Required: "True", DataTypeCode:"str", DropDownOptions: "", ColumnId: "1"},
"obj2":{Heading: "Test 2", Required: "False", DataTypeCode:"dropdown", DropDownOptions: "Alpha,Beta,Gamma,Delta", ColumnId: "2"},
"obj3":{Heading: "Test 3", Required: "True", DataTypeCode:"int", DropDownOptions: "", ColumnId: "3"}
};
And I'm passing it to a function that does this:
for (var col in columnData) {
r += '<td><input type="text" name="col' + col.ColumnId + '" value="' + col.Heading + '" /></td>'
}
A breakpoint in FireBug confirms that columnData is a valid object, it has three sub objects, and the sub objects have the expected properties and values. But this is the output I'm getting after the function is called:
<td><input name="colundefined" value="undefined" type="text"></td>
Unfortunately I think my lack of experience with JSON is making the results of my attempts to track the answer down unusable. How do I write a loop that will correctly get the sub objects of columnData?
3 Answers 3
You still need columnData:
columnData[col].ColumnId
Comments
JSON requires key values to be enclosed in double quotes, your columnData variable is a javascript object, not JSON.
That being said, col is the current key in columnData being iterated over, e.g. obj1, obj2, obj3. If you want to access a property of one of these objects, you need to access it first:
var col;
for (var key in columnData) {
col = columnData[key];
r += '<td><input type="text" name="col' + col.ColumnId + '" value="' + col.Heading + '" /></td>'
}
6 Comments
Do this:
var key;
var col;
for ( key in columnData ) {
col = columnData[ key ];
r += '<td><input type="text" name="col' + col.ColumnId + '" value="' + col.Heading + '" /></td>';
}
Another option:
r += Object.keys( columnData ).map( function ( key ) {
var col = columnData[ key ];
return '<td><input type="text" name="col' + col.ColumnId + '" value="' + col.Heading + '" /></td>';
}).join( '' );
I also recommend a templating engine (like Handlebars.js) for your HTML string concatenation needs.
.jsonfile (from the server) as a string, which is then parsed viaJSON.parseinto a JavaScript object. On the other hand, when you havevar obj = { ... };, that is an object literal and is not related to JSON.for...inworks is explained in the MDN documentation: developer.mozilla.org/en/JavaScript/Reference/Statements/…