0

I can't seem to figure out how to return a array from a JSON object. I have an object and I am trying to take the name property from the JSON object and put it into a global array called: itemNames =[];

This array is going to be used as arguments for another function.

var itemNames = [];
var itemsIds =[];
function itemArray() {
  fetch(url)
  .then(function(response) {
    return response.json();
  })
 .then(function(myJson) {
    let itemNames =[];
    let itemsIds =[];
    Object.values(myJson).forEach(e=> {
      itemNames.push(e.name);
      itemsIds.push(e.id);
    });
  })
 return itemNames;
}

itemArray();
console.log(itemNames);

Expected output:

itemNames =[item1, item2, item3]
Nick
  • 624
  • 8
  • 24
  • See the answers to the two linked questions (paricularly the "Why is my variable unaltered..." one). When your `console.log` runs, the `fetch` promise callbacks **haven't run yet**, so naturally the array is still empty as nothing has added two it yet. To fix it, return the result of the `fetch` chain and use `.then` on it (or use `async` and `await`). – T.J. Crowder Dec 24 '18 at 15:58
  • Side note: You have a common error in your `fetch` call: You're not checking `response.ok`. This is so common I [wrote it up on my anemic little blog](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). Before calling `response.json()`, you need that `ok` check. – T.J. Crowder Dec 24 '18 at 16:00

0 Answers0