astronomy-domine
astronomy-domine

Reputation: 103

Undefined value when adding data from JSON to array using .push()

I'm getting JSON data from this API. My code looks like this:

function setup() {
   noLoop();
   //Enable cross-origin request
	 let CO = 'https://cors-anywhere.herokuapp.com/';
   //API link
	 let source = 'http://hitchwiki.org/maps/api/?continent=AF';
	 let url = CO + source;
	 loadJSON(url, insertInToArray);
}

function insertInToArray(data) {
   var ids = [];
   var count = Object.keys(data).length;
	 for(let i = 0; i < count; i++) {
        let cod = data[i].id;
        ids[i].push(cod);
	 }
     console.log(ids);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>

When opening the console I get the error 'Uncaught (in promise) TypeError: Cannot read property 'push' of undefined'. Apparently before all the ID's there an undefined value but I really have no clue on how to fix it.

Thanks for the help!

Upvotes: 2

Views: 464

Answers (3)

HMR
HMR

Reputation: 39260

Data is an array so you can use map:

function insertInToArray(data) {
  var ids = data.map(
    function(item){ return item.id; }
  )
  console.log(ids);
}

Upvotes: 1

zmag
zmag

Reputation: 8241

do ids[i] = cod instead of ids[i].push(cod).

function setup() {
  noLoop();
  //Enable cross-origin request
  let CO = 'https://cors-anywhere.herokuapp.com/';
  //API link
  let source = 'http://hitchwiki.org/maps/api/?continent=AF';
  let url = CO + source;
  loadJSON(url, insertInToArray);
}

function insertInToArray(data) {
  var ids = [];
  var count = Object.keys(data).length;
  for (let i = 0; i < count; i++) {
    let cod = data[i].id;
    ids[i] = cod;
  }
  console.log(ids);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>

Upvotes: 1

MrLine
MrLine

Reputation: 688

I always use async and await to handle my JSON requests.

async function insertInToArray(data) {
    ...
    var count = await Object.keys(data).length;
    ...

Upvotes: 1

Related Questions