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.
Can you explain what is the problem, and how I can solve it.

fetchis asynchronous, soconsole.log(word),console.log(word[0]), ... happen before the data is requested. Thatconsole.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.readJsonasyncand addawaittofetch. Learn more about this here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…thenfunction 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 onword, do it inside the then.