Extracting the last element from a nested array in JavaScript (AirTable Scripting)

I am a beginner in JavaScript and am trying to use an API to update an AirTable. My background is in R, so I’m learning as I go. I need help pulling the latest vote from a ‘votes’ array for each bill retrieved. Below is my current attempt at the code, and I have omitted my API key for confidentiality.

// API setup 
let myApiKey = '(insert your API token here)';

// Specify the table to fetch bill data from
let myTable = base.getTable('Test Bills');

// Destructure to obtain records object from results
let { records } = await myTable.selectRecordsAsync();

// Logging records to verify success
console.log(records);

// Iterating through each record to retrieve bill information
for (let record of records) {
    // Fetching bill details using the API
    let billResponse = await remoteFetchAsync(`https://api.legiscan.com/?key=${myApiKey}&op=getBill&id=${record.name}`);

    // Parsing response into JSON format for AirTable
    let jsonData = await billResponse.json();

    // Inspecting data for the first object in the array
    console.log(jsonData.bill);

    // Attempting to access the last vote - this part is giving trouble
    const lastVote = jsonData.votes[jsonData.votes.length - 1];
}

I have two main questions regarding this implementation:

  1. How can I correctly assign the lastVote variable? I tried using length - 1, but it doesn’t seem to work as expected.
  2. Is there a more efficient method to retrieve the last item from an array instead of using the length property?

I would appreciate any help or insights into this issue!

Currently, I’m facing this error:

TypeError: Cannot read properties of undefined (reading 'length')
    at main on line 24

The error you’re encountering might be due to the jsonData.votes array being undefined or empty for some of the bills, likely causing the length property to be inaccessible. To handle this, you could first check if the array exists and has elements before attempting to access the last element:

const lastVote = jsonData.votes && jsonData.votes.length ? jsonData.votes[jsonData.votes.length - 1] : null;

This way, lastVote will be null if the votes array is undefined or empty, preventing the TypeError from occurring. This check is a simple, yet efficient, way to ensure your code doesn’t break due to unexpected data structures.