I have a JSON data set that's being deserialized and written into a textarea input in the form:
{
"key1": "",
"key2": "0",
"key3": "",
"key4": "0"
}
Using the following for loop:
for (var key in jsonObj.myData) {
textarea.value += key + ": " + jsonObj.myData[key] + "\n";
}
The text appears correctly in the textarea after this operation. Later, I serialize this data using the following for loop:
console.log(textarea.value); // Shows text with line breaks as expected
for (var line in textarea.value.split("\n")) {
console.log(line); // Shows only incrementing number
var keyval = line.split(": ");
json += "\"" + keyval[0] + "\": \"" + (keyval[1] || "") + "\",";
}
This results in serialized data which looks like this:
{
"0": "",
"1": "",
"2": "",
"3": ""
}
I would expect that splitting on "\n" would return an array of "key: value" strings as they were entered into the textarea, not (I assume) the index of the line. What am I doing wrong?
for-in
loop is iterating over the keys of the array, which are indices, returned by textarea.value.split("\n")
, not over the elements themselves.
var lines = textarea.value.split("\n");
for (var i = 0; i < lines.length; i++) {
// expected "key: value" string
console.log(lines[i]);
...
}