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

Tips for connecting an input tag within a popover to a Vue Model

I've got an input nested inside a popover content as shown below: JSFiddle Link HTML code snippet: <div id="vue-app"> <div class="btn btn-primary" data-toggle="popover" data-placement="bottom" title="Hello World!" data-html="true" data ...

The functionality of PHP in relation to the jQuery post feature seems to be malfunction

After developing the JavaScript functionality for this contact form, below is the HTML structure without any CSS styling included: <!-- Contact Form --> <div class="cws-widget"> <div class="widget-title" style="color:#fec20b;">S ...

I have implemented a bootstrap modal, but whenever I trigger a function on the JavaScript side, it automatically closes. I am aiming for the modal to remain open

<div id="responsive-modal3" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none; " data-keyboard="false" data-backdrop="static" ng-init = "populateBidSpocData()" > <div cl ...

Extracting data from a JSON object

Currently, I am facing an issue with my node.js code that is not working as expected when trying to fetch a value from a 3rd party website in JSON format. Although my code works fine for similar cases, it is failing to extract the price of a specific item ...

Should I serialize a 2D array in JSON format and send it as two separate arrays, or is

When it comes to sending a 2-dimensional array (along with several other variables) to PHP using jQuery.ajax(), I have a couple of options in mind: One option is to serialize to json using JSON-js Another option would be to send both arrays as csv string ...

Activate the HTML drop-down option upon selecting the radio button, or the other way around

I'm attempting to accomplish a task. Below is the code snippet I am working with: <form> <input type='radio' name='radio_flavour' checked/>Unique flavour<br/><input class='double-flavoured' type=&apo ...

Another option for handling a series of conditional statements instead of a bulky

Can someone help me with a coding issue I'm facing? I have an application that contains a large number of buttons which I need to trigger using keyboard presses. Currently, I am using a switch statement for this purpose. However, as the number of butt ...

Utilizing AngularJS to create bound checkboxes

I am struggling with two checkboxes, one with Data Binding and the other without Data Binding. The code snippet below illustrates this: <html ng-app="notesApp"> <head><title>Notes App</title></head> <body ng-contro ...

Export was not discovered, yet the names are still effective

There seems to be a slight issue that I can't quite figure out at the moment... In my Vue project, I have a file that exports keycodes in two different formats: one for constants (allCodes) and another for Vue (keyCodes): export default { allCodes ...

Button Triggering Javascript

Looking for a handy solution that allows users to either accept or reject a website's cookie policy. I came across an interesting library called cookies-EU-Banner (found at ) which seems to be quite popular. It recognizes when the user clicks on Reje ...

Sending Data Back to Main Function Using a Callback

When I try to call the emailExists() function, it should ideally return true or false. However, instead of that expected behavior, I am encountering this error: TypeError: cb is not a function Since asynchronous operations and callbacks are relatively ne ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

Optimizing the particle rendering speed for HTML5 <canvas> elements

Currently conducting an experiment to enhance the maximum particle count before frame-rates begin to decrease in HTML5 Canvas. Utilizing requestAnimationFrame and employing drawImage from a canvas as it appears to be the most efficient method for image re ...

I would like to split a string of characters using spaces XY XYZ XYZ

As a young developer, I am facing a challenge and seeking a solution. The user enters a number in a format like XX XXX XXXX, but I need it to be separated differently. Currently, the numbers are being grouped as XXX XXX XXX, which is not the desired outp ...

Transition from the previous image to the new one with a fading effect to enhance list item navigation

I've been working on implementing a sprite image for each list item (home, services, and contact) in my project. Using CSS, I've managed to move the position on hover successfully. However, I now want to add a fade effect to the transition instea ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

Transform information into a json structure

import enum import requests from bs4 import BeautifulSoup import json import pandas as pd headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.3" ...

Merging scripts to minimize HTTP requests - The Takeover of the Body Swappers

For my website design, I've implemented the Invasion Of The Body Switchers script from brothercake.com. This script involves loading three separate js files in the header. I'm looking to optimize my site by reducing the number of HTTP requests a ...

What is the best method for combining two JSON array files?

I am faced with the task of merging multiple files containing JSON arrays obtained through web scraping. The structure of these files is consistent and looks similar to this: db_1.txt [ {"title": "Title1", "price" : 21.37}, {& ...