When I request the value of a JavaScript object, I am met with 'undefined'

I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below:

function shop_info(name, latitude, longitude, type) {
    this.name = name;
    this.latitude = latitude;
    this.longitude = longitude;
    this.type = type;
}

After defining the object, I added data retrieved from an AJAX request to an array of 'shop_info' objects named 'all_shops'.

var i = 0;
for (var o in data) {
    var name = data[o].name;
    var type = data[o].type;
    var lat = data[o].lat;
    var lng = data[o].lng;

    all_shops[i] = new shop_info(name, lat, lng, type);
    i++;
}

However, when I try to access 'all_shops[i].name', it works fine, but when I attempt to access 'all_shops[i].lat' or 'all_shops[i].lng', it returns 'undefined'. I even tried parsing the lat/lng values with no success. Both lat and lng are double variables in my MySQL database. While I can retrieve the lat/lng values individually from the AJAX response data without any issues, problems arise when I put them into an array and try to access them. Any assistance on this matter would be highly appreciated. Thank you.

Answer №1

It is recommended to reference the latitude or longitude values from all_shops[i] instead of lat or lng. This is based on how your shop_data function is defined:

function shop_data(name,latitude,longitude,type)
{
   this.name=name;
   this.latitude=latitude;
   this.longitude=longitude;
   this.type=type;
}

If you prefer to use lat or lng, you can modify the shop_data function definition as follows:

function shop_data(name,latitude,longitude,type)
{
   this.name=name;
   this.lat=latitude;
   this.lng=longitude;
   this.type=type;
}

Answer №2

Alter from

this.latitude=latitude;
this.longitude=longitude;

to

this.lat=latitude;
this.lng=longitude;

An oversight was made during the editing process.

Answer №3

After updating variable names for consistency and doing some tidying up, the revised code looks like this:

function storeInfo(title,Lat,Long,category){
    this.title=title;
    this.latitude=Lat;
    this.longitude=Long;
    this.category=category;
}

Additionally:

var count = 0;
for(var obj in infoArray){
    var title = infoArray[obj].title;
    var category = infoArray[obj].category;
    var latitude = infoArray[obj].latitude;
    var longitude = infoArray[obj].longitude;

    allStores[count]=new storeInfo(title,latitude,longitude,category);
    count++;
}

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

The Javascript Date constructor struggles to interpret date strings in certain timezones that are not enclosed in brackets

Take a look at the examples below: new Date("Wed, 28 May 2014 09:50:06 EEST"); // Invalid Date new Date("Thu, 26 Jun 2014 09:09:27 EDT"); // OK, is parsed new Date("Wed, 28 May 2014 09:50:06 (EEST)"); // OK, is parsed new Date("Thu, 26 Jun 2014 09:09:27 ( ...

Stylish hover effects displayed on disabled button using Styled Components

I am currently working on a button using Styled Components. However, even when the button is in a disabled state (:disabled), it still exhibits hover behavior that should not be present. I am wondering if there is a proper way to prevent hover effects when ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

Get the large data file in sections

I ran a test script that looks like this: async function testDownload() { try{ var urls = ['https://localhost:54373/analyzer/test1','https://localhost:54373/analyzer/test2'] var fullFile = new Blob(); for (le ...

Guide: Building a Dropdown Form in Angular 2

I have a webpage with an HTML form that includes a button positioned above the form. I am interested in adding functionality to the button so that when it is clicked, a duplicate of the existing form will be added directly beneath it. This will allow for m ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

Tips for modifying the JSON array output into an object using PHP

I am encountering an issue with the API JSON output. I am experiencing some difficulties with the JSON output when it comes to looping through, as it seems to create its own indexes despite my attempts to force the array format into an indexed array. Here ...

Every day, I challenge myself to build my skills in react by completing various tasks. Currently, I am facing a particular task that has me stumped. Is there anyone out there who could offer

Objective:- Input: Ask user to enter a number On change: Calculate the square of the number entered by the user Display each calculation as a list in the Document Object Model (DOM) in real-time If Backspace is pressed: Delete the last calculated resul ...

Implement using a variable as a key for an object in a reducer function

I am facing an issue with constructing an object. The string, named "SKU" in this scenario is being passed through action as action.name. Although I have all the necessary data in the reducer function, I need to dynamically replace the hardcoded SKU with ...

Is it possible to save the project by generating incremental JSON diffs?

In the process of developing a web-based paint program, I have implemented a system where the user's artwork state is saved as a json object. Each time an addition is made to the client's undo stack (which consists of json objects describing the ...

Alternative technologies that have the capability to execute DTO request response similar to WCF

My current WCF service allows me to submit a request using a DTO and responds with another DTO for my WPF application. For instance, I can send a filter object for products containing filtering properties and additional paging information, and in return, r ...

I am facing an issue with my Angular 11 CLI application while trying to set it up with Jest. The specific error message I am encountering is: "TypeError: Cannot read property

Having issues with my Angular 11 cli app and Jest integration. Whenever I run npm run test, specifically jest --updateSnapshot, I encounter the following error in my terminal: Error: TypeError: Cannot read property 'paths' of undefined Here is ...

Issues with APIs surfaced following the transition from DataGridPro to DataGridPremium

In my current project, we initially implemented the MUI X DataGrid but later switched to DataGridPro due to business requirements. Recently, we upgraded our plan from Pro to Premium which has caused some unexpected issues in our existing code. I am using " ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...

The React engine is triggering an error stating "Module not found."

Utilizing react-engine to enable the server with react component access. Through react-engine, you can provide an express react by directing a URL and utilizing res.render. The documentation specifies that you need to supply a path through req.url. app.use ...

Utilize JavaScript to extract and exhibit various SQL records stored within a multidimensional array

How can I use JS, JQuery, PHP, and MySQLi to automatically generate an HTML table within a div on a webpage? The table should display data based on user-input search criteria. For example, the user enters a start date and end date, clicks a button, which t ...

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...

React's useState Hook: Modifying Values

I just started learning about React and React hooks, and I'm trying to figure out how to reset the value in useState back to default when new filters are selected. const [apartments, setApartments] = React.useState([]) const [page, setPage] = React.us ...

Generating JSON using while loops and foreach loops in PHP

Currently, I am in the process of updating a PHP application that generates JSON data on the server side. {"by":"Industrie LLC","dead":false,"descendants":396,"id":"396","kids":[1,396],"score":396,"time":"396","title":"Industrie LLC","type":"comment","url ...

Managing numerous asynchronous requests and subsequent responses

Dealing with numerous ajax responses is my current challenge. It's important to note that each request may vary in completion time. It can be quite tricky when it comes to distinguishing between successful and failed requests. Any tips on how to dete ...