-1

I have a JSON file with gallery of images inside. I am extracting that data with a function , but i want , once that data is extracted to store it into a variable , so that from now on i can use that variable for data reference. How can i do that

function getJsonphotos() {
    $.getJSON("./json/photos.json", displayImages);
}

function displayImages(data) {
data.forEach(function (item) {
    storeContainer.append(`<<img id=${item.id} src=${item.location} />)
  });

 let jsonArrayVariable = [] ; 

How should i place the photos in the jsonArrayVariable variable.

Jefry90
  • 89
  • 8
  • 1
    `jsonArrayVariable = data`? Really depends on what you are trying to do though. You should have a look at [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) and https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html – Felix Kling Nov 04 '19 at 12:16
  • not clear what exactly want you to re-use `data` or `jsonArrayVariable` – Egor Nov 04 '19 at 12:17

2 Answers2

1

You create an array outside of the callback function. Then push every item to the array.

let jsonArrayVariable = [];
function displayImages(data) {
data.forEach(item => {
    storeContainer.append(`<img id=${item.id} src=${item.location} />`);
    jsonArrayVariable.push(item);
  });
zimmerbimmer
  • 908
  • 7
  • 24
0

i did it like that :

arrayImages = [];
function getJsonphotos(data) {
    $.getJSON("./json/photos.json",function (data){
    arrayImages = data; 
    displayImages(data);
  });
}
Jefry90
  • 89
  • 8