Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split on newline-delimited textarea.value returns array of line indices

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]);
  ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading