When using the console, I am able to access JSON items, but unfortunately they do not appear when using console.log

After converting a CSV file to JSON and adding custom headers for some mysterious reason, my data now appears like this:

https://i.sstatic.net/H7Ls0.png

Within my JavaScript file, I have the following line of code:

console.log(jsonData.theData[0].symbol);

However, when I try to execute it, I receive the error message:

admin.js:46 Uncaught TypeError: Cannot read property '0' of undefined 

From my perspective, it seems like '0' is defined. Oddly enough, when I run the same command directly in the browser console, it works perfectly fine.

https://i.sstatic.net/Thyi6.png I have also attempted the following:

JSON.stringify(jsonData.theData[0])

Unfortunately, this results in the same error. Any thoughts on why this might be happening?

Below is the content of my JavaScript file:

    var jsonData = {};
var theData = [];

document.getElementById("fileToRead").addEventListener("change",function() {
     var input = document.getElementById("fileToRead");

        for(var i = 0; i < input.files.length; i++){
            var files = input.files[i];
            Papa.parse(files, {
            header:false,
            dynamictyping:true,
            complete:function(results){
                var input = results.data;
                input.forEach(function(input){
                    jsonData.theData = theData;

                    var singleEntry = {
                        "symbol"    : input[0],
                        "date"      : input[1],
                        "open"      : input[2],
                        "high"      : input[3],
                        "low"       : input[4],
                        "close"     : input[5],
                        "volume"    : input[6]
                        }

                    jsonData.theData.push(singleEntry);
                })
                //console.log (jsonData);
               // document.getElementById("editor").innerHTML = JSON.stringify(jsonData);
                } // End Complete - Callback
            }); // End PapaParse
    } // End for loop
console.log(jsonData);
});

An update...

Upon adding some console.logs, here's what was revealed:

https://i.sstatic.net/yRCEH.png

Answer №1

Make sure to click on the small i icon. There seems to be a race condition occurring where your object is not being loaded in time for the

console.log(jsonData.theData[0].symbol);
line of code. The Inspector is stepping in to load it for you after the fact.

Answer №2

When you make a call

to console.log(jsonData.theData[0].symbol);

Do you confirm that jsonData is properly loaded?

Edit (after updating JS code)

In your JavaScript code, the line

console.log(jsonData.theData[0].symbol);
seems to be missing.... It's hard to pinpoint the error without seeing it.

In any case, as mentioned earlier, even if you place console.log(jsonData); at the end of the loop, it might still return empty because data is being loaded asynchronously

source

As file parsing happens asynchronously, ensure you have a callback function.

Hence, there is a possibility that your jsonData remains empty (i.e., not loaded)

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

Utilizing the index of the .map function in conjunction with internal methods

After running my code, I encountered the following error message: Warning: Encountered two children with the same key, `classroom-1278238`. Keys are required to be unique so that components can maintain their identity during updates. Having non-unique keys ...

When the window.onbeforeunload event is triggered, the user is directed back to

After making changes on a page with a form, I would like to automatically save those changes without requiring any confirmation from the user. After researching on this question, I modified one of the answers to fit my needs. It's important to note t ...

Objects remaining static

I'm currently working on a VueJS component that has the ability to export data into .xlsx format. To achieve this functionality, I am utilizing the json2xls library, which requires an array of objects with identical keys (representing column names) to ...

Issues with loading a 3D model on my hosting platform

After successfully testing my web page locally, I uploaded it to my server and encountered an issue with my 3D model not loading. What could be causing this problem? The code snippet responsible for loading the 3D model is as follows: textureLoader = new ...

What causes the first button to be clicked and the form to be submitted when the enter key is pressed within a text

Start by opening the javascript console, then place your cursor in the text box and hit enter. What is the reason for the function "baz" being called? How can this behavior be prevented? function foo() { console.log('foo'); } function bar() ...

How can I effectively handle JSON arrays in Swift programming?

Currently, I am directly parsing JSON data from an array without using a model class. I would appreciate any suggestions on the most efficient way to parse JSON data, whether it be through utilizing a model class or by directly parsing the JSON data. ...

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

Fine-tuning CSS layout based on perspective alteration

I am working with the following code: function exportTableToExcel(tableID, filename = ''){ var downloadLink; var dataType = 'application/vnd.ms-excel'; var tableSelect = document.getElementById(tableID); var tableHT ...

What are the best practices for binding JSON data with nested objects to an ASP.NET MVC ViewModel?

Consider the following code snippet on the client side: var vm = { Input : "Label: Value", Rules : [ { Name : "RemoveString", Params : [ "Label: " ] } ] }; $.post("/API/ApplyRule", vm, function(data) { }); Now, let&apos ...

Accessing the app module in separate files is not possible for Angular and Coffeescript

As I work on managing and refactoring my Angular code in a Rails project with CoffeeScript, I am facing issues accessing Angular objects between multiple files. Here is the current file structure: javascripts |-Angular |-controllers | |-search_strl.js ...

Total of Vue Component Subtotals

One of the challenges I'm facing in my Vue app is calculating the total of subtotals. Every component has its own subtotal that depends on user input. I need to combine these individual subtotals and display the result in an input field outside of th ...

When using Vuejs + Laravel to make an Ajax request, only the most recent information entered into the view is submitted

Can someone guide me on implementing a basic ajax request using Vue with my Laravel backend? I have a boolean field called completed in a table named courses. In the view, users can see all assigned courses and toggle their completion status by pressing a ...

Fill the next Thursday with JavaScript

I'm having trouble updating the date for the upcoming Thursday using JavaScript. The current script works fine until the end of the month, but if it's the 25th of August, the output will be "Next Thursday - 8/32/2022". I need a more intelligent s ...

Encountering Next.JS Router Issue: Unable to Access Properties of Null (specifically 'useContext')

As a beginner in Next.js and React, I'm facing an issue with redirecting users from the "Projects" page to the Product Page Details. Here's the code snippet I am using: const openProjectDetails = () => { Router.push('/api/' + props ...

Error message: "Despite using the 'use client' function in Next.js, a ReferenceError occurs as 'window' is undefined."

What is the reason for the server running this hook when "use client" is included? It does not lead to any application crashes, everything functions with no errors, but an error is logged at the const [windowWidth, setWindowWidth] = useState(window.innerWi ...

Unable to update state from within a function in react

As I delve into the realm of coding, a simple graph catches my eye. It showcases various data sets including current, all, and filtered data. Initially, the first block of code runs smoothly. However, upon attempting to setState in order to make some modif ...

JavaScript and CSS animations out of sync in terms of timing

I've been encountering some issues. I have an array containing 5 lines of text that change with a timer, but it seems that the css timer animation might not be synced properly or my @keyframes slidesdown setup could be incorrect. The delay between te ...

Is there a Rust secp256k1 alternative to the `crypto::ECDH::computeSecret()` function in NodeJS?

After developing a functional NodeJS/Javascript function, I am now intrigued by the idea of achieving similar results using the Rust secp256k1 library: /* * Calculate the Symmetric Key from the Public and Secret keys from two * different key pairs. * ...

Using preventDefault on an anchor tag with the tel: protocol is ineffective

When a user clicks on a telephone number it should do nothing on desktop and on mobile it should call the number. Finding a solution seemed straightforward by using return false or preventDefault on desktop, but that approach has not proven effective so fa ...

The SVG format quickly displays new and larger datasets on line charts without any transition effects

My goal is to create a line chart with animated transitions similar to this demo, but without the dots. I am attempting to integrate this functionality into a react component where the update method can be triggered by another component, allowing the d3 op ...