I’m pretty new to JavaScript and working on an AirTable script that pulls data from an external API. The main issue I’m facing is getting the last item from a nested array called “votes”.
Here’s my current setup:
// API configuration
let myApiKey = '(secret_key_here)'
// Connect to the table
let billsTable = base.getTable('Legislative Data')
let { records } = await billsTable.selectRecordsAsync()
// Process each record
for (let item of records) {
// Make API request
let response = await remoteFetchAsync(`https://api.example.com/?token=${myApiKey}&action=getData&bill_id=${item.name}`)
let result = await response.json()
console.log(result.legislation)
// This line fails - trying to get the most recent vote
const mostRecentVote = result(result.voting_data.length - 1)
}
I keep getting this error: TypeError: Cannot read properties of undefined (reading 'length')
Two main questions:
- What’s the correct way to grab the last element using the length property?
- Is there maybe a simpler approach to get the final array item?
I think my syntax is wrong but I can’t figure out the right way to do it. Any help would be great!
Yeah, the parentheses are your main issue, but I learned something the hard way on a similar API project.
APIs love changing their response structure without warning. I spent hours debugging when our vendor randomly renamed fields.
Here’s what I do now:
// Get the voting data safely
const votingData = result?.voting_data || result?.votes || []
// Multiple ways to get the last item
const mostRecentVote = votingData[votingData.length - 1] // classic way
// or
const mostRecentVote = votingData.slice(-1)[0] // also works
The slice(-1)[0] approach is neat because it won’t throw errors on empty arrays - just returns undefined.
Add some logging right after your API call:
console.log('Full API response:', Object.keys(result))
console.log('Voting data type:', typeof result.voting_data)
This saved me countless times when APIs returned different field names than expected. Way easier than guessing what broke.
Yeah, the syntax error’s from using parentheses instead of square brackets, but here’s another thing to consider. AirTable automation scripts can be really finicky with API responses, so I always add a fallback chain. Try destructuring with defaults at the top: const { voting_data = [] } = result, then use voting_data[voting_data.length - 1] safely. AirTable’s runtime hates undefined properties and this has saved me from production failures more times than I can count. Also, some APIs paginate their vote arrays or nest them way deeper than you’d expect. I’d log the actual structure of result first - you might find votes are stored somewhere completely different.
Your syntax is wrong on that line. You wrote result(result.voting_data.length - 1) but you need square brackets, not parentheses: result.voting_data[result.voting_data.length - 1]. The error makes me think voting_data might be undefined though. Add a check first: const mostRecentVote = result.voting_data && result.voting_data.length > 0 ? result.voting_data[result.voting_data.length - 1] : null. This’ll prevent crashes when the data isn’t structured like you expect. I’ve hit this same problem with APIs that sometimes return empty arrays or missing properties.
Indeed, the issue is with your use of parentheses instead of square brackets. A better approach is to use result.voting_data.at(-1) as this will return the last element directly and handle empty arrays gracefully. However, ensure that voting_data is defined before accessing it. To debug further, consider logging the entire response object using console.log(JSON.stringify(result, null, 2)) to verify what data you’re actually receiving, as APIs can sometimes return unexpected structures.
you’re missing error checking. check if the data exists first: if (result.voting_data && Array.isArray(result.voting_data)). also, fix those parentheses - should be square brackets like everyone said. apis can return weird stuff, so always validate the structure before accessing it.