1

my Json-file is a simple Object with 2 arrays:

{ 
"key1": ["a", "b", "c"],
"key2": [ "d", "e", "f"] 
}

in Javascript I'm using fetch to get the data. To use the data I'm pushing it into an array

const jsonData = '/things.json';
const myArray = [];

fetch(jsonData)
.then(answer => answer.json())
.then(data => myArray.push(data))

console.log(myArray); //this gives me a nested array

console.log(myArray[0]); //undefined 

putting myArray through a loop also gives me an //undefined

using the spread syntax or concat gives me //Found non-callable @@iterator

How can I get the content of that array?

1
  • 1
    your console.logs are occuring before your .then. Move them inside of the function being passed to .then and you should be fine. Commented May 27, 2020 at 10:31

3 Answers 3

1

As pointed by @Gavin , Your console.log statement should execute after fetch has completed. One of the ways to do that would be to add that in another then.

fetch(jsonData)
.then(answer => answer.json())
.then(data => myArray.push(data))
.then(() => console.log(myArray[0]));

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

After you receive the JSON data Simply use const array=Object.values(jsonData)

I meant

fetch(location).then((response)=>{
response.json().then((data)=>{
const array=Object.values(data)

Comments

0

What you need to do is this:

const jsonData = '/things.json';
const myArray = [];

fetch(jsonData)
.then(answer => answer.json())
.then(data => myArray.push(...data)) //Notice the spread operator

UPDATE Seems like spread operator is not working in your project you can do this too:

const jsonData = '/things.json';
const myArray = [];

fetch(jsonData)
.then(answer => answer.json())
.then(data => myArray = data);

For ... not to work on your projects, there could be various solutions, one of them being changing target in tsconfig to "target": "es5"

2 Comments

Thank you for the suggestion. The spreadsyntax gives me: Found non-callable @@iterator
@strangePotatoe basically just to avoid nesting, what I was doing was this: var a = [1, 2, 9, 5, 7]; myArray.push(...a) so myArray will now be [1, 2, 9, 5, 7]; This should work. The reason why it's not working is your project might not be supporting ... spread operators. See the updated answer then.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.