Hello i am new in JavaScript and i would like to know how to get an array of objects with strings and an array with numbers. Is it possible to use parseInt to convert the array with the numbers in my CSV ?
this is my CSV-Data
word; arrayInt
hello; [1,20,30]
bye; [4,50,60]
this is my output
[{"word":"hello"," arrayInt":" [1,20,30]"},{"word":"bye"," arrayInt":" [4,50,60]"}]
the code i use with the CSV-Data at the top
<head> </head>
<body>
<form id="myForm">
<input type="file" id="csvFile" accept=".csv" />
<br />
<input type="submit" value="Submit" />
</form>
<script>
const myForm = document.getElementById("myForm");
const csvFile = document.getElementById("csvFile");
function csvToArray(str, delimiter = ";") {
// slice from start of text to the first \n index
// use split to create an array from string by delimiter
const headers = str.slice(0, str.indexOf("\n")).split(delimiter);
// slice from \n index + 1 to the end of the text
// use split to create an array of each csv value row
const rows = str.slice(str.indexOf("\n") + 1).split("\n");
// Map the rows
// split values from each row into an array
// use headers.reduce to create an object
// object properties derived from headers:values
// the object passed as an element of the array
const arr = rows.map(function (row) {
const values = row.split(delimiter);
const el = headers.reduce(function (object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}
myForm.addEventListener("submit", function (e) {
e.preventDefault();
const input = csvFile.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const text = e.target.result;
const data = csvToArray(text);
var myJSON = JSON.stringify(data);
console.log(myJSON); // Output of the CSV-Data
var tmp = myJSON;
for (var i = 0; i < tmp.length; i++) {
let member = tmp[i];
let arr = JSON.parse(member.arrayInt);
tmp[i].arrayInt = arr;
};
console.log(tmp);
};
reader.readAsText(input);
});
</script>
</body>
the output i want to achieve
[{word:"hello", arrayInt: [1,20,30]},{word:"bye", arrayInt: [4,50,60]}]