0

I am new to the world of JavaScript and JSON. I have a JSON file with words in multiple languages. What I want to do is to group all words by same language, so that each of it will be in a separate array. Goal is that if I choose 'French' as langauge I get word = ['Bonjour','comment', 'ca', 'va']

This is my JSON file

{
    "Sheet1": [
        {
            "English": "Hello",
            "French": "Bonjour"
        },
        {
            "English": "my",
            "French": "mon"
        },
        {
            "English": "friends",
            "French": "ami"
        }
    ]
}

This is the code I have.

const my_array = ["English", "French"]
const word = []
function readJson()
{
    fetch('./data.json')
    .then(response => response.json())
    .then(data => {
        for (let index = 0; index < data.Sheet1.length; index++) {
            word.push(data.Sheet1[index][our_language])
        }
    })
    console.log(word)
    console.log(word[0])// Want to display first element, but can't
    console.log(word[1])//Want to display second element, but can't
}
readJson()
console.log(word)

Problem is that I can't display to console each element of this array separately, but I can see that element are present in the whole array.

Console

Can you explain what is the problem, and how I can solve it.

Rony Cohen
  • 85
  • 7
  • `fetch` is asynchronous, so `console.log(word)`, `console.log(word[0])`, ... happen before the data is requested. That `console.log(word)` shows the data is a result how the console of the browser handles the display of the data. This is explained in more detail in the duplicates. – t.niese Jul 13 '22 at 16:26
  • Make the `readJson` `async` and add `await` to `fetch`. Learn more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – Andrei Surdu Jul 13 '22 at 16:28
  • @t.niese Do you have a solution for the problem. I see duplicates but for a beginner like me it's look very complicated – Rony Cohen Jul 13 '22 at 16:28
  • Put your console.logs inside the `then` function immediately preceding. You won't be able to return anything meaningful from readJson, unless it's a promise, so if you were planning on calling another function to operate on `word`, do it inside the then. – James Jul 13 '22 at 16:50

0 Answers0