Attempting to extract data from a csv file, I utilized the following code snippet: (The csv file contains multiple lines representing different rows in a table)
var newArray = []
function init() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var lines = this.responseText.split("\n");
newArray.push(lines)
}
}
xhttp.open("GET", "CMDBsox.csv", true);
xhttp.send();
}
window.onload = init;
console.log(array)
The format of the csv file is as follows:
(Note: The first element of each line is not surrounded by quotes)
First line: Lorem1, "Lorem2", "Lorem3", "Lorem4",...
Second line: Ipsum1, "Ipsum2", "Ipsum3", "Ipsum4",...
and so on
I appended the 'lines' array to a new array named newArray
.
Currently, all rows are within another array like below:
0:(21) [...]
0:["Sample1", "Sample2", "Sample3,...]
1:["Example1", "Example2", Example3",...]
2:["Test1", "Test2", "Test3",...]
Continuing...(occurring 21 times)
To access the different arrays(rows), I use:
"newArray[0][0]", "newArray[0][1]", "newArray[0][2]",...
However, I am currently facing three issues:
While I can retrieve them via console, I encounter an error when accessing it through code. For instance, using
newArray[0][1]
results in a
However, the whole array is visible in the console?**"TypeError: array[0] is undefined"**.
How can I create sub-arrays within the main array? Currently, I have a large string within
newArray[0][0]
, but I require individual elements in an arrayMy aim is to access each "line" using
newArray[i]
instead ofnewArray[0][i]
. How do I shift them into the top-level array to eliminate the redundant initial array?
Appreciate your assistance :)