Array logging mistakenly outputs a number

I needed to access the data from JSON outside of the xml function so that I could use it in multiple functions. When I initially logged the data, it displayed arrays with objects in it. However, when I checked the length instead, it returned zero. After researching, I discovered that this discrepancy occurred because both functions were running synchronously. To address this, I delved into promises and implemented the following:

let allTasks = []

// Read data
const dataPromise = new Promise((resolve, reject)=>{
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status ==200) {
            const myData = JSON.parse(this.responseText)
            allTasks = allTasks.push.apply(allTasks, myData)
            resolve()
        }
    }
    xhttp.open("GET", "data.json", true);
    xhttp.send();
})
    
dataPromise.then(()=>{
    dataUse()
})

// Show data
dataUse = () =>{
    console.log(allTasks)
    // All variables
    const todos = document.querySelector('.todo')
    const todoInput = document.getElementById('new-todo')
    const added = document.getElementById('added')
    const itemsLeft = document.querySelector('.items-left > span')
    
    allTasks.forEach((datas)=>{
        const todo = document.createElement('div')
        todos.appendChild(todo)
        
        const input = document.createElement('input')
        input.setAttribute('type', 'checkbox')
        input.setAttribute('id', datas.name)
        input.setAttribute('class', 'checks')
        todo.appendChild(input)
        
        const label = document.createElement('label')
        label.setAttribute('for', datas.name)
        label.setAttribute('class', `${datas.name} tasks`)
        todo.appendChild(label)
        
        const span = document.createElement('span')
        label.appendChild(span)
        
        const paragraph = document.createElement('p')
        paragraph.innerHTML = datas.todo
        label.appendChild(paragraph)
    })
}

However, after logging the data now shows a number rather than an array with objects, hindering the proper functioning of the function.

So, how can I rectify this issue?

Answer №1

The issue arises from not realizing that there is no need to assign the return value of a push operation to a variable since it simply returns the length of the array. By pushing into the array directly, the variable will automatically contain the most recent content.

Instead of using

allTasks = allTasks.push.apply(allTasks, myData)
, try simply using allTasks.push(allTasks, myData).

It is recommended to utilize const over let whenever possible.

const allTasks = [];
allTasks.push(allTasks, myData);

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

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

Struggling to get Angular to properly sanitize inputs using ng-bind-html

I've been struggling to figure out the issue in my code for an entire day with no success. At this point, I'm reaching out for help. My problem arises when trying to utilize ng-bind-html-unsafe within a template. As a newcomer to Angular, it&apos ...

The column must have a defined value and cannot be left empty

I encountered an issue while trying to populate a database with seed data. The error message I received is: name: 'SequelizeDatabaseError', parent: Error: Column 'id' cannot be null code: 'ER_BAD_NULL_ERROR', errno: 1048, sql ...

JavaScript loop through an array of objects

Is there a way to loop through and retrieve all of the addresses? const name = { john: [ { age: 21, address: 'LA', } ], sam: [ { age: 26, address: 'California' } ] } I have tried using th ...

Issue encountered: Failure in automating login through Cypress UI with Keycloak

Struggling with automating an e-commerce store front using Cypress, specifically encountering issues with the login functionality. The authentication and identity tool in use is keycloak. However, the Cypress test fails to successfully log in or register ...

Switching minimum and maximum input values based on a specific condition: A step-by-step guide

I am looking for a way to reverse the minimum and maximum values of two input elements that I have defined. Is there a way to achieve this using HTML or JavaScript (Angular)? Here is an example of what I am trying to do: <label> Width: < ...

Concealing numerous tables depending on the visibility conditions of subordinate tables

I have the following HTML code which includes multiple parent tables, each with a specific class assigned to it: <table class="customFormTable block"> Within these parent tables, there are child tables structured like this: <table id="elementTa ...

What is causing the width discrepancy in my header section on mobile devices?

Help needed with website responsiveness issue! The site works fine on most screen sizes, but when it reaches around 414px in width, the intro section becomes too wide for the screen. Any ideas on what could be causing this problem? html: <nav id="m ...

What is the best way to retrieve JSON data in a React application?

useEffect(async () => { const fetchPostData = async () => { const response = await axios("") setPosts(response.data) } fetchPostData(); }, []) Rendering : posts.map(post => <li>{post.name} ...

Utilize a function to send an AJAX email

In my JavaScript function, I have been attempting to send an email from a contact form. The validation checks are working correctly, but when the code reaches the point of sending the form, it gets stuck and doesn't receive any response from $.ajax. I ...

When you hover over an image, both the image's opacity and the color of the title beneath it change. However, if the title expands to two lines, it messes up

I am currently working on a project where I have an image and a title displayed below the image. My goal is to change the color of the text when hovering over the image, as well as adjust the opacity of the image. Additionally, when hovering over the title ...

Guide to verifying current data using the jQuery validation library combined with CodeIgniter 4 in the presence of automatic CSRF protection

I am currently working on validating a form using the jQuery validation plugin and CodeIgniter 4. I have enabled CSRF protection that auto generates for each request. Initially, I can successfully validate the form on the first request. However, on subsequ ...

Is it possible to directly add a child in HTML from nodejs?

I'm in the process of developing a chat application that requires users to select a room from a list of available rooms stored in <datalist> options, which are fetched from a SQL table on the server. Within my login.html file, users are prompte ...

Collecting Images Based on Quantity

Despite using async to download URIs on every request and closing when a certain count is reached, I am still encountering the issue of files not being downloaded properly and exiting before reaching their maximum. Can someone suggest the best solution t ...

Combine several objects into one consolidated object

Is there a way to combine multiple Json objects into one single object? When parsing an array from AJAX, I noticed that it logs like this: 0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", ...} 1:{id: "25", user: "Jim ...

Oh no! There seems to be an unexpected token "<" in my React Native project on Visual Studio Code

When utilizing react-native in VS Code, I encounter an issue where my code fails to compile and throws a syntax error for the "<" symbol. Strangely, many tags work fine with "react-native run-android" from the Terminal. This is the code snippet that I ...

Tips for achieving the Bootstrap 5 Modal Fade Out effect without using jQuery or any additional plugins apart from Bootstrap

I'm facing some challenges in achieving the fade out effect in Bootstrap 5 modals. I am aiming for something similar to the "Fade In & Scale" effect demonstrated here: https://tympanus.net/Development/ModalWindowEffects/ It is crucial for me to accom ...

"Repetitive" elements arranged horizontally

My goal is to create a looped row of elements, similar to this design: This row should function like a carousel where clicking the "Next" button changes the current element and positions it in the center of the row. I envision this row as being looped, wi ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

The ng-model failed to display the updated value until a click was made somewhere on the page

I am struggling with displaying the correct value of an ngModel variable defined in my controller. Despite changing to the correct value in the console, it doesn't update on the page until I click somewhere else or hit the update button again. Here&a ...