1

I am successfully able to call the API and get the full list to display in the console. However, when I try to pull out single elements, I get "undefined". I can not see what I am doing wrong. Below is my code:

let myHeaders = new Headers();
myHeaders.append("X-eBirdApiToken", "someToken");

let requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
};

class Birds {
    constructor(region) {
        this.region = 'US-MA'
    }

    async getBirds() {
        const response = await fetch(`https://api.ebird.org/v2/data/obs/${this.region}/recent`, requestOptions);
        const data = await response.json();
        console.log(data);
        console.log(data.comName);
        console.log(data["locId"]);

        const {speciesCode, comName} = data;
        console.log(speciesCode, comName)

        return data;
    }
}

Below is a sample output from the API as I am getting 283 rows:

281:
comName: "Catharus sp."
howMany: 1
lat: 42.219
lng: -71.064
locId: "L207351"
locName: "Blue Hills Reservation"
locationPrivate: false
obsDt: "2020-07-10 11:50"
obsReviewed: false
obsValid: true
sciName: "Catharus sp."
speciesCode: "cathus"
subId: "S71320255"

__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

And when I try to get the individual items:

undefined
birds.js:20 undefined
birds.js:23 undefined undefined
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
crawlings
  • 61
  • 6

1 Answers1

0

This line shows that you're trying to deconstruct a single object,

 const {speciesCode, comName} = data;

However, data is an array! So instead, if you want to console log, you need to do,

 const {speciesCode, comName} = data[0];
Nicholas Harder
  • 1,496
  • 10
  • 15
  • Thank you, this solved the question. However, I know realize I was trying to skip a step. I need to run a for loop first, and then work with the individual objects. – crawlings Jul 21 '20 at 13:57