Difficulty encountered when trying to retrieve the data stored within the ARRAY

I am fairly new to JavaScript and I have encountered a peculiar issue while trying to access items stored in an Array within a JavaScript object.

Code

var Exp = {"no":Array(), "dateFrom":Array()}
readData();
function readData() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', sheet, true);
    xhr.onload = function () {
        if (this.status === 200) {
            const response = JSON.parse(this.responseText);
            const feeds = response.feed.entry;
            feeds.forEach(function (post) {
                Exp["no"].push(post.gsx$no.$t);
                Exp["dateFrom"].push(post.gsx$from.$t);
            });
        }
    }
    xhr.send();
};
var lengthNo = Object.keys(Exp.no).length;
var valueZero = Exp.no[0];
console.log(lengthNo, valueZero, Exp);

Console result

0 undefined 
{no: Array(0), dateFrom: Array(0)}
no: (4) ["1", "2", "3", "4"]
dateFrom: (4) ["02/2001", "07/2006", "11/2008", "03/2014"]
__proto__: Object

When running this in the console, everything works perfectly. Any idea why it's not functioning correctly in the script file?

Answer №1

To properly handle the data retrieval process, it is imperative to reposition the following code snippet:

var lengthNo = Object.keys(Exp.no).length;
var valueZero = Exp.no[0];
console.log(lengthNo, valueZero, Exp);

within the xhr.onload function block:

xhr.onload = function () {
    if (this.status === 200) {
        const response = JSON.parse(this.responseText);
        const feeds = response.feed.entry;

        feeds.forEach(function (post) {
            Exp["no"].push(post.gsx$no.$t);
            Exp["dateFrom"].push(post.gsx$from.$t);
        });

        var lengthNo = Object.keys(Exp.no).length;
        var valueZero = Exp.no[0];
        console.log(lengthNo, valueZero, Exp);
    }
}

This adjustment is necessary due to the asynchronous behavior exhibited by the xhr request.

Answer №2

If you want to access the contents of your specific object, you can use the Object.keys() method which will give you an array of all the properties. In this case, since the object contains arrays under the keys no and dateFrom, you can directly retrieve the values by referencing Exp.no.

var Exp = {"no":["1", "2", "3", "4"], "dateFrom":["02/2001", "07/2006", "11/2008", "03/2014"]}
var lengthNo = Exp.no.length;
var valueZero = Exp.no[0];
console.log(lengthNo, valueZero, Exp);

Answer №3

If you're looking for a straightforward method, consider this simple approach. Here's how you can create a JavaScript object:

const Experience = {number: [], startDate: []};
const numberLength = Experience['number'].length || Experience.number.length;
const firstValue = Experience['number'][0] || Experience.number[0]; // This will output 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

What is the approach for utilizing Vue List Rendering with v-if to verify the presence of items within an array?

My current implementation utilizes v-if to conditionally display a list of cafes. However, I am interested in filtering the list based on whether a specific drink item is found in an array. For instance, I have a collection of cafes and I only want to dis ...

AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user ...

Personalized HTML Input Field for Digital Keyboard Scores

As a new JavaScript beginner, I have experimented with various approaches in an attempt to create a website that features a digital piano experience without the actual instrument. My goal is to develop a platform where pressing multiple keys together will ...

Tips for managing extended HTTP requests

I am dealing with a lengthy http request that involves a lot of computation on the back-end. Currently, everything is synchronous, which means that while the server computer is processing, the browser does not receive any output or result. Eventually, the ...

Calculating the mean of student scores using a two-dimensional array

I'm having trouble calculating the average for my student grades. Even though I follow the instructions and return the AVG to 0, the output remains the same as before. My teacher advised me to reset the average to 0, but I'm unsure where to make ...

Remove the active class after it has been clicked for the second time

Currently, I am working on a menu/submenu system where I want to toggle active classes when clicked. However, I encountered an issue - if the same menu item is clicked twice, I need to remove the active class. Initially, I tried using jQuery's toggleC ...

Can Browserify be used with AngularJS to bundle directive templateUrls using relative paths?

Currently, I am developing a web application using AngularJS and Browserify to bundle my JavaScript files into a single package for use on the webpage. My project structure looks something like this: app |-index.html |-index.js |-bundle.js |-components ...

Received undefined instead of a Promise or value from the function in Nodemailer

I'm currently exploring cloud functions and trying to implement email notifications for document creation triggers in Firestore. I found a helpful tutorial that guided me through the process, but I encountered an error while analyzing the cloud functi ...

What is the process for accessing a URL using a web browser and receiving a plain text file instead of HTML code?

Hello there! I've created a simple HTML file located at that can display your public IP address. If you take a look at the code of the page, you'll notice that it's just plain HTML - nothing fancy! However, I'm aiming for something mo ...

What type of element should I utilize - a submit button, a standard button, or a hyperlink - to execute this task?

After setting up a feed of comments retrieved from a MySQL database using PHP, I am now looking to allow users to upvote these posts. This would involve adding one of the following options to the existing code: <? $con = mysqli_connect("localhost","us ...

I lingered a moment too long on the left and right buttons of my Carousel

Currently facing an issue with a slideshow feature where the images are not smoothly transitioning when using the left/right buttons. The transition is either delayed, slow, or causes the page to hang. Additionally, after some time, the images automaticall ...

Strange behavior exhibited by the HTML DataList component within an Angular application

I have created a simple component that displays a list of data and allows users to add new entries. <h6 *ngIf="withHeader"><label for="select"> {{title}} </label></h6> <label *ngIf="!withHeader" [ngClass]="{'required&apos ...

Interested in receiving a concise, text-only snippet from a WordPress article?

In my custom theme template, I am utilizing "The Loop" to fetch the most recent three posts from WordPress. <?php $args = array( 'numberposts' => 3 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?&g ...

There seems to be an issue with the SimpleSchema: The modifier is appearing empty after removing keys that are not in the schema

I implemented a new SimpleSchema for my collection. Below is the definition and schema of the collection: GIST Upon calling this method from the client side: export const setEventInvitationStatus = new ValidatedMethod({ name: 'events.updatePartici ...

Why is it that despite passing all the unit tests successfully, the function fails when used in its actual context with the same parameters?

I have created a basic API to encrypt text using the Caesar cipher in Javascript with Express.js. While running tests with Jest, it seems that all the tests are passing successfully (and a console.log of the output confirms that the resulting string matche ...

Attempting to dynamically change the text of a button in JavaScript without any user interaction

I have created a button function that displays a word's definition when clicked. However, I am now attempting to modify it so that the definitions are shown automatically every few seconds using "SetInterval" without requiring a click. I am unsure of ...

Issue: Module '/Users/MYNAME/Desktop/Projects/MYPROJECTNAME' not found

I am currently in the process of compiling Node using TypeScript, and I'm still getting acquainted with it. An issue I encountered was that my /src files were not being updated when I made changes and restarted the server. To troubleshoot, I decided ...

Leveraging Angular for dynamic HTML form type setting

I've been experimenting with Angular in order to create a form that includes all the properties of an object. Among these properties are passwords, and I want Angular to utilize the password form type for them. Currently, I have managed to make it wo ...

perform Transpose on a 4-dimensional numpy array

My Python code includes a 4D array containing a batch of 10000 images, where each image has 5 channels and dimensions of 25x25. Therefore, the shape of the 4D array is 10000x5x25x25. I am looking to transpose the images, but currently using nested loops f ...