I'm encountering an issue where the array is coming back empty after adding elements from JSON. Any tips on how to fix

I am currently working with a .JSON file where I have read the data and implemented a for...in loop to iterate through it.

After using console.log, I noticed that while I can view the data in the console, I am unable to add any data to an array using the push function. When I try to log the array, it appears empty.

My main question is: how can I successfully add the data to the array?

Below is the code snippet:

let wordList = []

fetch("wordleanswers.json")
    .then(response =>response.json())
    .then(data=>{
        let myWord = data.toString()

        for (const singleData in data){
            wordList.push(singleData)
        }
    })

console.log(wordList)

I'm wondering if there is something crucial that I might be overlooking?

EDIT: In case it helps, here is a .txt version of the .json file containing the text within an object: https://github.com/MissingFable/wordle_bot_4_python/blob/main/wordleanswers.TXT

Answer №1

Utilize asynchronous code to retrieve the data. Make sure to await the fetch request before outputting your array.

Consider using then at the end as shown below.

let wordList = []

fetch("wordleanswers.json")
    .then(response =>response.json())
    .then(data=>{
        let myWord = data.toString()

        for (const singleData in data){
            wordList.push(singleData)
        }
    }).then(() => {
      console.log(wordList)
    })

Alternatively, encapsulate the code within an async function and use await before calling the fetch function.

Edit: Including another solution using IIFE function

(async () => {
  let wordList = []

  const response = await fetch("wordleanswers.json")
  const data = await response.json()
    

  for (const singleData in data){
     wordList.push(singleData)
  }

  console.log(wordList)

})()

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

Executing JavaScript in Page Object Model

When working on my automation script using Java with Selenium and the Page Object Model, I sometimes find it necessary to utilize Javascript Executor. This is because default WebDriver clicks can result in exceptions when elements are not found. Within th ...

Initiating iOS UIWebView when the DOM is fully loaded

One issue I'm facing is that UIWebView triggers webViewDidFinishLoad before its content is actually rendered, resulting in a short delay after the view is displayed before the content appears. I'm curious if there's a way to trigger an event ...

Checking for empty inputs using Html, JavaScript, and CSS

I need help with a form that has 6 input fields. I want to ensure all fields are filled out, and if not, display an alert message. Any suggestions on how to achieve this? Additionally, I'm experiencing difficulties implementing different font styles. ...

Is it common to have numerous operations in a single controller in AngularJS?

<!DOCTYPE html> <html ng-app="myApp" > <head> <title>myApp.html</title> </head> <body ng-controller="myCtrl as vm"> <br><br> <div> <p> I ...

Attempting to create a fixed-length file parser from scratch

I am currently working on developing a parser that can handle fixed-length files containing multiple records separated by newline characters, with each record consisting of varying segments. The goal is to parse this data into a POJO and then export it to ...

"Troubleshooting: Why is my JSON feed returning null with jQuery getJSON

There seems to be an issue with the data being returned as null. Unfortunately, I do not have direct access to resolve this problem. A server admin will need to update the feed according to my requirements. If you know of a solution that does not involve m ...

How to return a variable to Express when clicking a button?

Imagine having a list of 10 elements, each with a unique id as their name, and the user has the ability to add more items to the list at any time. If I were to click on an element, my goal is to have Express retrieve the id of that specific element. If it ...

Exploring extensive arrays using numpy

I have two sets of integer arrays. arr1 = numpy.array([1109830922873, 2838383, 839839393, ..., 29839933982]) arr2 = numpy.array([2838383, 555555555, 2839474582, ..., 29839933982]) The length of arr1 is approximately 15,000 and the length of arr2 is aroun ...

JQuery causes Bootstrap carousel to malfunction after dynamically adding attribute to img tag

If you're thinking of sending me to this resource: Bootstrap Carousel not working after adding items dynamically with jQuery, know that the situation described there is different from mine. My issue involves fetching paths for 3 images from a JavaScr ...

Shifting Hues: The Liquid Rainbow Transformation

I'm attempting to modify the liquid rainbow script's color scheme to various shades of purple exclusively, but I am struggling to make it work. The script is located in the CodePen editor. [Access CodePen Editor Here][1] [1]: https://codepen ...

Restrict the size of AJAX response

As I work on my decentralized application where I only have control over the client and not the servers, I am looking to implement measures to prevent malicious activities. One of the important considerations is preventing DoS attacks on the client through ...

Unsuccessful CORS on whateverorigin.org with YQL

Despite trying all three methods, I keep getting an error regarding cross domain access denied. Previously, I had successfully used YQL in different parts of my applications, but now it seems to have stopped working as well. JSFIDDLE <script> $(fun ...

Regular expressions can be used to extract specific attributes and inner content from a div element within a contentEditable container

Context I am currently developing a tagging system called @Name for my website. Successfully, I have managed to detect names upon keystroke and replace the content with the corresponding div class='tag' data-id='User-id'>Name</di ...

Sharing a controller between directives in AngularJS

While trying to implement an angularjs directive, I encountered some difficulties in sharing a controller between directives I am unable to access the enterUser directive from the controller below app.directive('entires', [function () { retur ...

I wonder if there is a method to verify whether pipelining is activated in PHP or JavaScript?

Is there a method to determine if pipelining is enabled in PHP or JavaScript? Certain browser services can be accessed in about:config that improve the speed of the browser without question, so I am interested in checking some of these and obtaining their ...

Strange flickering/visualization issue experienced with transparent MeshPhongMaterial in Three.JS

In my scene, I have a Mesh called cylinder: const cylinder = new Mesh( new CylinderGeometry(2, 2, 1, 32), new MeshPhongMaterial({ color: color, shininess: 32, opacity: 0, transparent: true, specular: 0xffff82, }), ); I made the ...

scala handling missing fields during JSON serialization in json4s

I've been utilizing json4s for serializing scala map objects. import org.apache.spark.util.StatCounter import org.json4s.DefaultFormats val myMap: scala.collection.Map[String, Map[String, StatCounter]] = Map("key" -> Map("secondKey" -> StatCou ...

Ways to dynamically assign a name to a div using AngularJS

Currently, I am in the process of developing a download function for an Android app using Angularjs based on this tutorial: Utilizing the Progress event in PhoneGap file transfers Everything seems to be working efficiently as planned; I can successfully d ...

What method does Node.js use to determine if the initial parameter in a callback function is designated as an error handler?

Recently, I've been delving into the world of Node.js and trying to grasp its error-first callback style. I'm intrigued by how a function discerns whether the first parameter is meant for handling errors or for other purposes, especially conside ...

I have a JSON object with a nested "src" value that I want to display on my webpage using Vue. How can I target and select this specific value?

I am currently working with an API and attempting to access a nested object within the JSON data named "Species Illustration Photo". Inside this object is an "img" property with the source link. How can I display this nested img source in my HTML using Vue ...