Tips for managing an "undefined" error when converting a CSV file to JSON with the Papa Parse framework

Let's take a look at my JavaScript code snippet:

function initiate(){
    let jsonData = parseCSVFile();
    console.log(jsonData);
    let csvData = transformCSVData(jsonData);
    console.log(csvData);
}

function parseCSVFile(){
    let parsedJson;
    let chosenFile = document.getElementById('fileInput').files[0];
    Papa.parse(chosenFile, {
        complete: function(results) {
            parsedJson = results.data;
            console.log(results.data);
            console.log(typeof(results.data));
        }
    });
    return parsedJson;
}

function transformCSVData(inputJSON){
    let newCSV = ""; // will be modified later
    let dataColumn = ""; // will be modified later
    let dataRow = ""; // will be modified later
    for (let i = 0; i < inputJSON.length - 1; i++) {
        // modifications to be made here in the future
    }
    return newCSV;
}

Next, I have included this script in my test HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src=".\transformCSV.js"></script>
    <script src=".\node_modules\papaparse\papaparse.js"></script>
    <input type="file" id="fileInput">
    <input type="button" value="Click Here!" onclick="initiate()">
</body>
</html>

When attempting to access the length of jsonData, an error message appears in the Chrome console:

Uncaught TypeError: Cannot read property 'length' of undefined
. Why is it showing undefined? It clearly exists in the console! What could be causing this issue and how can I resolve it? Is there a way to handle jsonData as a static JSON object?

Answer №1

In the complete callback function, you are assigning a value to parsedJSON. However, this assignment is likely happening AFTER the parseCSV function has already returned an undefined value for parsedJSON. To fix this issue, consider rewriting your code using a callback or promise to ensure proper sequencing.

parseCSV(function (myJSON) {
  console.log(myJSON);
  let myCSV = transformCSV(myJSON);
  console.log(myCSV);
});

function parseCSV(callback){
  let parsedJSON;
  let selectedFile = document.getElementById('fileIn').files[0];
  Papa.parse(selectedFile, {
    complete: function(results) {
        parsedJSON = results.data;
        callback(parsedJSON);
    }
  });

}

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

Prevent the end of the scroll from causing a new scroll to start?

In the code snippet provided, there are two divs. When scrolling down past the end of the blue div, the overall body/div also scrolls down. Is there a way to prevent this additional scrolling effect once reaching the scroll boundary of the blue div? For e ...

Can Selenium be used to test a Siebel Open UI application?

Can I use Selenium JavaScript to interact with the Siebel application without any additional add-ons? ...

"Utilize openlayers' map.updateSize function to automatically adjust the map size in response to

When trying to display a side panel, I want to ensure that the map's proportions stay within the new div width or height. Currently, the map is simply resized, causing the countries to appear distorted. I attempted to use map.updateSize without succes ...

Experimenting with sails.socket using npm for testing purposes

Currently, I am utilizing sails.js v0.11.0 and delving into unit testing. While I have a good grasp on testing normal controllers through http requests, I am at a loss on how to approach testing the same calls via socket requests. Any recommendations for ...

Possible undefined object in React Redux

I'm encountering a Typescript issue where Redux object I am utilizing is potentially undefined, even though I have not specified its type as potentially being undefined or set it to be undefined anywhere in my code. /redux/globalSettings/actions.ts ...

Proper method for calling a function within a specific scope

I am utilizing user-contributed modules that I aim to avoid editing in order to make upgrades easier. My goal is to enable users to browse for a CSV file on the local filesystem, parse it, and display it in a dynamic table. For this task, I am using PapaP ...

How to troubleshoot Django's Jquery datatable aoData not functioning issue

Getting Started with Datatable Initial Data Setup object_list=[{'username': u'Paul', 'phone_number': u'9910087044', 'user_group__name': '', 'manager_name': ' ', 'role&ap ...

Is there a method we can use to replace fixture fields with data created during the test case to produce a dynamic payload? (Already attempted existing solution)

I am new to using Cypress and I'm wondering if there is a way to generate a dynamic payload by replacing values in a JSON file with values generated programmatically in a Cypress test. This is similar to what we do in Rest Assured by substituting %s i ...

Utilizing Sinon.js for inline callbacks upon successful execution

Currently, I am utilizing QUnit, Sinon.js (specifically fakeServer), and jQuery (for AJAX) to capture and test AJAX calls within my program. One issue that I am encountering pertains to the inconsistency where inline-function calls are not being executed. ...

Obtain a compilation of users who have expressed their reaction to a message with a specific emoji on Discord

Check out this Discord.js code snippet for a Discord bot: client.channels.fetch('channelID here').then(function (channel) { channel.messages.fetch('messageID here').then(function (message) { console.log(message.reactions.cache.get(&a ...

Utilizing Google Maps to display an infowindow upon clicking a location from a geojson file

I want to implement info windows that pop up when markers on a map are clicked. I used the sample code provided by Google (below) to create a marker map from geojson files dragged and dropped into the window. My goal is for the info windows to show text ta ...

My Angular custom libraries are having issues with the typing paths. Can anyone help me troubleshoot what I might be doing

After successfully creating my first custom Angular library using ng-packagr, I encountered an issue where the built library contained relative paths specific to my local machine. This posed a problem as these paths would not work for anyone else trying to ...

Is there a way to receive information from the server without the need to press the "submit" button?

Below is a message I have: <h3 id="welcomeUsername">Hello, </h3> I am looking to trigger this script: function loadPage(){ $.get( "/fetchUser", function( data ) { $( "#welcomeUsername" ).append( data ); alert ...

Attempted to incorporate images into a listview resulted in java.lang.NullPointerException

I attempted to create a listview that includes images and text, but I encountered errors that are disrupting the normal functioning of my application. When I tried debugging, the process dialog started loading for 5-10 minutes before the application just r ...

I need help fixing a JSON Enum Schema problem - Can someone provide me with a correct

In this JSON Payload, I am attempting to include an ENUM type value for a specific element. { "firstName" : "firstName", "lastName" : "lastName", "systemIds" : [ { "systemName" : "SAP", "systemId" : "99c27c63-e0b6-4585-8675-7aa3811eb4c3" } ...

Eliminate Video Time Indicator

Can the video progress bar be removed from this specific video player? I would like it to be integrated into the embed code that I share with others. <iframe id="hapyak-player-157199-8825" marginwidth="0" marginheight="0" frameborder="no" scrolling=" ...

How can I incorporate Bootstrap multi-select into the jQuery DataTables DOM?

Having trouble implementing a bootstrap multi-select inside a jQuery datatable DOM. I followed this example to add a custom element within the jQuery datatable container. It works fine for normal bootstrap select, but when trying to add a bootstrap multi-s ...

Encountering a problem when trying to set the value in the controller and receiving unexpected output from the console

Attempting to assign a value to an object and show it in the view, but encountering an issue. When setting the vm.order.info.when to 'Any Value' and logging the vm.order.info, the value appears correct at first glance. However, upon inspecting th ...

Error: Python expected a string or bytes-like objectTypeError

Currently, I am attempting to tally the number of components based on the data from a json file. Outlined below is my current approach: # Function to count the components def get_component_count(data, component_name, locator_name, counter=0): if re.m ...

React Native (or React) utilizes separate TypeScript modules to detect and respond to style adjustments for dark mode

Objective: Add a dark mode feature to a react native application. A brief overview of the system: File structure: Profile.ts ProfileCss.ts constants.ts In my app, I've organized styles in separate .ts files and exported them as modules to keep them ...