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

Is there a way to place two input fields from different forms side by side on the same line?

Here are two forms extracted from an html page: <form method="get" action="search/s" id="number"> <div style="text-align: center;"> <input type="text" id="regNo" name="regNo" size="30" maxLength="50" > or ...

Incorporating Node.JS variables within an HTML document

After building a simple site using Express, I discovered that Node.js variables can also be used with Jade. exports.index = function(req, res){ res.render('index', { title: 'Express' }); }; This is the code for the index file: ext ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

Creating a nested object in React's handleChange method: a step-by-step guide

Hey there, I've been working on an onChange function called handleChange for a set of dynamically created inputs. This function receives the event and then performs the following actions: const handleChange = (e) => { const updatedValues = [...va ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Utilizing an AngularJS custom filter twice

Experimenting with a custom Angular filter example found at: https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter, my version looks like this: <!DOCTYPE html> <html> <script src="http://ajax.googleapi ...

The retrieved information remains unchanged even after modifications are made on the subsequent Next.js server-side rendered page

I'm facing an interesting scenario with my application. It consists of two main pages - one displaying user account statistics and the other allowing users to edit these statistics. Both pages are rendered on the server side. When I navigate to the fi ...

What is the method for retrieving the XMLHttpRequest errors registered with addEventListener?

I am struggling to find a solution. https://i.stack.imgur.com/bRJho.gif ...

What is the best way to display the key names of objects using jsonpath?

Currently, I am utilizing nodejs in conjunction with jsonpath. Within my json structure lies: { things:{ books: [ {name: "book1"}, {name: "book2"}, {name: "book3"}, {name: "book4"}, ], movies: [ {name: "movie1"} ...

Combining two arrays with varying lengths based on their values

Seeking assistance with a programming task that is straightforward yet challenging for me. There are two arrays: one long and one short. var arrayShort = [ { id: 'A', name: 'first' },{ id: 'B', name: &ap ...

Module is absent in JavaScript but present in TypeScript

As I delve into coding a vscode extension by following a tutorial, I encountered an issue with importing in my server.ts file. The directory structure looks like this: ...

Library for YAML or JSON with inheritance support

We are in the process of developing a new service that requires reading configuration settings from a file. Currently, we are utilizing both YAML and Jackson for deserializing the YAML data. One unique aspect of our project is that we need to have the abil ...

Which HTML element does each script correspond to?

Are there any methods to identify the script used in certain HTML elements? For instance, if I wish to determine the script responsible for creating a drop-down menu, I can locate the HTML and CSS for the menu but not the JavaScript (or other scripts). I ...

Encountering an error while trying to run the command "npm run start" due to an issue of "EMFILE

After running npm update, my project start broke. When I try to use npm run start, it returns the following error: 10% building 0/1 entries 0/0 dependencies 0/0 modulesnode:internal/errors:484 ErrorCaptureStackTrace(err); ^ Error: EMFILE: too many ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

What is the best way to fill an array within an object using React Hooks?

I am encountering an issue with an object that includes an array. Here is the code snippet in question: const [data, setData] = useState({ jobs: [] }); Currently, I am retrieving data from an API and need to append this fetched information to the jobs arr ...

Leveraging the power of Fractal Transformer in conjunction with ember-data

While using the PHP league's Fractal as the transformer for my API, I have encountered an issue where the item transformer is wrapping everything in an array similar to a collection. This goes against the standards set by the JSON API. For instance, ...

The Json library's parse() function was unable to resolve a basic parsing issue

I'm encountering a compile time error on Json.parse in the code snippet below, with the message cannot resolve symbol parse. Despite passing in an eventData parameter of type String, and considering that parse() accepts a string input, why is this ope ...

Utilize Webpack to import a file containing exclusively global constants

I have a specific file filled with essential global constants that I am attempting to bring into another JavaScript file. This way, I can utilize these constants within the code of the second file. globalConstant.js global.RoutesOffersPage = { routes: ...

Managing configuration variables in ExpressJS for various environments

Is it possible to set a variable for different environments when defining the environment? app.configure 'development', () -> app.use express.errorHandler({dumpExceptions: true, showStack: true}) mongoose.connect 'mongodb://xxx:<a h ...