Convert Array from JSON File into a Javascript Array does not work

23
April 22, 2019, at 02:00 AM

even though I read alot of related articles about this topic on stackoverflow, I cant figure out what im doing wrong here.

So I have a json (peak.json) file with multiple objects and one array (audiopeakdata). It looks like this:

{"version": 2, "channels": 1, "data": [0.1, 0.3, 0,3 ... 0.1]}

Now I want to read the data-array from the json file and want to parse it into a an javascript array:

var array = [];
$.getJSON('peak.json', function(data) { 
    array = data.data;
}); 
console.log(array);

But the console log shows that the array is empty - how can that be?

Thanks for your help

Answer 1

It's becuase you are trying to return data from a callback which doesn't work. Use async/await:

async function getData() {
  var data = await $.getJSON('peak.json')
  var array = data.data;
  console.log(array);
}
getData();

Or move your console.log inside callback:

var array = [];
$.getJSON('peak.json', function(data) { 
  array = data.data;
  console.log(array);
});
READ ALSO
Accessing parent callback function in nested child components

Accessing parent callback function in nested child components

I'm trying to create a globally accessible modal by implementing this modal in a top-level component in React NativeTo achieve this, I try to extend SwitchNavigator (based on this link) with a callback function and make this accessible through navigation...

18
Webpack, JavaScript generated HTML with Images

Webpack, JavaScript generated HTML with Images

I have a json file with an array and in it are multiple urls for images:

61
how can I renew or destroy old page in react native

how can I renew or destroy old page in react native

I have some trouble when I choose in the picker and go a new page after that when I back to the picker again and I choose a new one the navigation the previous page i have 2 page

28
How to map between enums based on identical key names?

How to map between enums based on identical key names?

I have two enums with identical key names, and I want to be able to use a value from one enum to get the value from the second enum

38