Having difficulty accessing a JSON imported object beyond the FOR loop

I am facing an issue when trying to reference my imported JSON data. The problem arises when I attempt to access the data outside of a FOR loop, resulting in the error message "Uncaught TypeError: Cannot read property 'Tname' of undefined"

The following code snippet works as intended:

for (var i in towns) {
    if (i == 1) {
        ctx.fillText(towns[i].Tname, 0, 0);
    }
}

However, the next line triggers an error with the message "Uncaught TypeError: Cannot read property 'Tname' of undefined", placed right after the above loop.

ctx.fillText(towns[1].Tname, 0, 0);

Despite trying various approaches, all attempts have failed so far. The output for "towns[1]" is displayed as "[Object Object]".

For those who are curious, here is a snippet from the towns.json file:

{"towns":[
    {"Tid":"2057277", "Tname":"York"},
    {"Tid":"2057575", "Tname":"Yanchep"}
]}

This portion of code handles the conversion to towns[] using JSON:

var towns[];
$.getJSON('towns.json', function(data) {
    for (var i in data.towns) { 
        towns[i] = data.towns[i]; 
    } 
});

Answer №1

Appreciate all the valuable input you have provided. The solution to my problem turned out to be related to syntax differences inside and outside the FOR loop. @Bergi, your guidance really helped me navigate in the right direction.

//Successfully executed within the loop
ctx.fillText(cities[i].Cname, 0, 0);

//Encountered an error with this syntax outside the loop
ctx.fillText(cities[1].Cname, 0, 0);

//Resolved the issue by using this syntax outside the loop
ctx.fillText(cities[1]['Cname'], 0, 0);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for JSON refusing to accept an element from an array?

I am looking to retrieve the exchange rates for all currencies from an API using an array that lists all available currencies. Below is the JavaScript code I have written: var requestURL = 'https://api.fixer.io/latest'; var requestUrlstandard ...

Utilize JavaScript to submit the FORM and initiate the 'submit' Event

Hey there! Here's the code I've been working on: HTML : <html> <body> <form enctype="multipart/form-data" method="post" name="image"> <input onchange="test();" ...

Adjusted position of the viewport if the DOM element containing the renderer is not located at the top of the display

I've come across an issue with a three.js scene within an Angular custom directive in the view. At the top, there's a navigation bar for switching between views (pretty standard so far). I set up a simple scene with a cube and basic camera rotati ...

Selenium - Tips for entering text in a dynamically generated text field using Javascript!

I'm fairly new to the world of web scraping and browser automation, so any guidance would be greatly appreciated! Using Python's Selenium package, my objective is: Navigate to Login using the provided username & password Complete my order thr ...

As a newcomer to Javascript, I am currently working on developing a CRUD-based application and could use some assistance with implementing the Edit functionality

I am currently in the process of developing a Javascript CRUD application that showcases data within an HTML Table. I have successfully implemented the Create, Read, and Delete functions. However, for the Edit function, I am looking to display the data in ...

Interact with visible elements by automating mouse clicks with puppeteer

When attempting to click on various elements within a page, my goal is to do so only if they are visible. While achieving this in selenium with the is_displayed method was simple, I have struggled to find a similar approach in puppeteer. I attempted to imp ...

Retrieve a zip file using React and Node from a RESTful API

I have an application built with React and Node where I have a table that includes a download button. Clicking the download button triggers a request to my Node app, which in turn should call a REST API to download a zip file directly into the browser. In ...

Minimize unnecessary rendering in React when toggling between tabs

I am currently working on a React application that utilizes material-ui to generate tabs. <div className={classes.root}> <AppBar position="static"> <Tabs value={value} onChange={handleChange}> <Tab label="Item One" /> ...

Tips for accessing CSS properties on the img tag

I could use some assistance with CSS. I am in the process of creating a tree structure using many <ul> and <li> tags. The issue arises when I have multiple <li> elements with a specific class, each containing an <img> tag. How can ...

Traveler encountering Flask website displaying 500 error on Dreamhost platform

I'm struggling to configure Passenger with Flask on my DreamHost server. The Flask site is running inside a virtualenv with Python 3.5.2. The goal is to take input from a query string in the URL, parse a JSON file on the server, search for the given q ...

Using jQuery to select the third element from every group of six

I am attempting to select the 3rd .foo element out of every set of 6. To clarify, here is a brief example: 1 2 3 (this) 4 5 6 1 2 3 (this) 4 5 6 and so on... So far, I have only managed to target every 3rd element, which is not exactly what I need beca ...

How can I convert an xlsx file to JSON using ExcelJS in Node.js?

https://github.com/guyonroche/exceljs I am a beginner with exceljs and just came across the description of exceljs on github. The description states: "Read, manipulate and write spreadsheet data and styles to XLSX and JSON." I am looking for a way to ...

A guide on passing JSON data to jQuery autocomplete

Hello everyone, I'm looking for assistance on how to integrate this JSON data with the jQuery autocomplete plugin. Being new to jQuery, I am unsure of the steps involved... [{"0":"1","id":"1","1":"Albania","country":"Albania"}, {"0":"2","id":"2","1 ...

Exploring the power of Django: Leveraging AJAX requests and utilizing path

I am currently exploring ways to pass variables to a specific JavaScript file that initiates an AJAX request within Django. Assume we have a URL with a path parameter linking to a particular view: url(r'^post/(?P<post_id>\d+)/$', Tem ...

Should private members be kept confidential during program execution?

While Typescript's "private" members may not be truly private at runtime, traditional closures maintain the privacy of their members. Is there value in ensuring that private members remain private during runtime? ...

Create a separate server session specifically for handling an ajax request?

Currently, I am working with a collection of PHP server-side scripts that manage user session state by utilizing PHP sessions extensively for authenticated users. For the client side within a mobile application and using Jquery ajax, I am striving to esta ...

Can you provide some insight on how to store XMLHttpRequest response in Javascript for future

I have a function in my codebase that is responsible for loading HTML templates asynchronously: loadTemplate: function(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open("GET" ...

What is the appropriate way to notify Gulp when a task has been completed?

I have been working on developing a gulp plugin that counts the number of files in the stream. Taking inspiration from a helpful thread on Stack Overflow (source), I started implementing the following code: function count() { var count = 0; function ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

Ways to tackle object references using a personalized Jackson deserializer

{ "title": "example", "elements": [ { "name": "x", "type": "TEXT" }, { "name": "y", &q ...