Saving csv data from an XMLHTTPRequest into an Array using Javascript

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:

  1. 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

    **"TypeError: array[0] is undefined"**.
    However, the whole array is visible in the console?

  2. 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 array

  3. My aim is to access each "line" using newArray[i] instead of newArray[0][i]. How do I shift them into the top-level array to eliminate the redundant initial array?

Appreciate your assistance :)

Answer №1

I am puzzled by your decision to shift the focus of your question from reading a file to copying a table elsewhere.
It is important to ask clear questions in order to receive accurate answers.

Inserting an array within another array may not be the best approach; consider using Object.assign instead.

var arr1 = [ 1,7 ,3 ,4 ,5];

var arr2 = [[]];


Object.assign (arr2[0], arr1)

console.log ('arr1 ...: ', JSON.stringify(arr1));
console.log ('arr2[0] : ', JSON.stringify(arr2[0]));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identifying the URL being accessed by an Android application

I developed an application for both iOS and Android that makes a php request to a server. In order to ensure security, I need to prevent users from manually entering the same URL in a browser - only the app should be able to make this request. I have con ...

Simple guide to identifying when the content of a dropdown option changes using jQuery

I am seeking a solution for detecting changes in the options of a dropdown field that are updated dynamically. Is there a method to capture an event each time the set of options within the dropdown is modified? I am not looking to track individual option ...

Converting a 3D image array in NumPy to a 2D array

I am working with a 3D-numpy array representing a grayscale image. Here is an example of how it looks: [[[120,120,120],[67,67,67]]...] Since it is a gray image, having every R, G, and B value the same is redundant. I am looking to create a new 2D array t ...

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...

Transmitting data from the backend to AngularJS during page load

After diving into Angular JS for the first time, I've hit a roadblock at an essential stage. My setup consists of an AngularJS front end and Grails backend. Check out the code snippets below along with my query. URL Mapping entry: as "/graph"(cont ...

Using PHP's preg_match function to store data in separate index arrays

My goal is to iterate through an array containing integers and save the matches in unique indexes of the array that increase by 1. However, currently all matches are being stored in a single index, which is set at zero. Below is the code I am using: for( ...

Make sure that the click event listener is set up on the anchor element so that it also affects its children

Currently, I have implemented a click event listener on my anchor elements. However, the anchors contain a span element within them, and the event listener does not function properly if you click on the span inside the anchor. document.addEventListene ...

Exploring Flask: A Guide to Dynamically Choosing Image Paths in Templates

I have created a Flask application to display subsets of large image collections stored on my local NAS. These images are microscopy images of cultured cells used for scientific research. The app allows me to compare 10-20 images at a time and includes syn ...

Conceal elements on a webpage using Python's Selenium WebDriver through the execution of JavaScript code

I am looking to use a python script to hide elements on a canvas element using javascript. Here is what I have attempted: def hide_elements(): driver = LiveLibrary.get_webdriver_instance() js_script = '''\ ...

Error: The method api.createContextKey is not defined while running the Next.js development server

I am currently facing an issue while attempting to start the development server for my Next.js project. The problem arises when I try to incorporate MUI into my project, resulting in these specific errors. The error message points to a TypeError related to ...

Receiving numerous requests within the useEffect Hook

In my voting system, users can vote "Yes" or "No", where clicking "Yes" sets the state to up and clicking "No" sets it to down. The voting functionality works well in the voteHandler method, but the issue is that I have to manually refresh the page after e ...

Extracting and retrieving data using JavaScript from a URL

After reviewing some code, I am interested in implementing a similar structure. The original code snippet looks like this: htmlItems += '<li><a href="show-feed.html?url=' + items[i].url + '">' + items[i].name + '& ...

"Encountered a hindrance while duplicating a file within an array:

#!/bin/sh i=0 while read line do for WORD in $line do #store in an array array[$i]=$WORD i=$((i+1)) done done < ACTION_TAG.txt File has been saved with the name .sh I am attempting to store a file in an array, ...

Final parameter of Array.Copy and Buffer.BlockCopy

Array.Transfer(sourceArray,targetArray,length); Buffer.MoveBlock(sourceArray,startInSource,targetArray,startInTarget,Length); Is the value of Length sourceArray.Length or should it be calculated as sourceArray.Length * sizeof(type)? The variable type re ...

jQuery: Implementing JavaScript on a page asynchronously through Ajax without triggering execution

When utilizing jQuery to execute an ajax request and insert code into my page, the added code includes both HTML and JavaScript. It seems that the JavaScript code is not being executed! What steps can I take to ensure that the newly added JavaScript sourc ...

Angular Express encountering URL mismatch when retrieving files post-refresh

Currently, I am developing a small MEAN stack application. One of the features is that when an image is clicked, it displays a partial containing information about the image. Everything was working fine initially. However, after refreshing the page, Angula ...

What could be the reason for encountering a TypeError while attaching event listeners using a for loop?

When attempting to add a "click" event listener to a single element, it functions correctly: var blog1 = document.getElementById("b1"); blog1.addEventListener("click", function(){ window.location.href="blog1.html"; }); However, when I try to use a for l ...

Ways to reverse engineer HTML, CSS, and JavaScript code into HTML format

Help needed! I am trying to edit the user interface but all the code is in one line and I can't figure out how to decompile it back to its original state. Can anyone offer assistance with this? <html lang="en"><head><meta char ...

Updating charts in React using Chart.js with the click of a button

I am currently learning React and Chart JS, but I have encountered an issue. I am unable to change the data by clicking on a button. Initially, the graph displays: var Datas = [65, 59, 80, 81, 56, 55, 69]; However, I want to update this graph by simply p ...

The functionality of reading JSON data from mongoexport is not supported by node.js

I recently exported a collection from MongoDB using the command below: mongoexport -d <database-name> -c <collection-name> -o foo.json The export was successful and generated foo.json file with the following content: { "_id" : { "$oid" : " ...