'Adding elements to array from JSON is returning empty array. How can I stop this? [duplicate]

I have a .JSON file, I've read the data and am using a for...in loop to loop through it.

If I use console.log, then I can print the data to the console, but if I try to add data to an array using the push function and console.log the array, I get an empty array.

Basically, how do I add the data to the array?

The code:

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)

Is there something I'm missing?

EDIT: Here is a .txt version of .json file (the text is just in an object in the .json): https://github.com/MissingFable/wordle_bot_4_python/blob/main/wordleanswers.TXT



Solution 1:[1]

You are calling an async code to fetch the data. You need to await on the fetch before you log your array.

Try to use then at the end. Like 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)
    })

Or you can put this whole code in async function and put await before fetch function call.

Edit: Adding the other 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)

})()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tauqeer Nasir