Encountering the issue of receiving an "undefined" response while attempting to retrieve an object property in JavaScript

I am currently developing a leaflet map to display agencies with dynamically created markers. Additionally, there is a list of agencies where clicking on each agency will automatically zoom in on the corresponding marker on the map. Now, I want to show agency information in a popup when either the agency card or the marker itself is clicked. While successfully achieving this for marker clicks, I am facing issues when implementing it for agency card clicks. To pinpoint the problem, I have outlined my approach below:

Firstly, here is my HTML code snippet for the cards:

 <div class="card border border-secondary rounded" onclick="moveMap({{ agency.latitude }}, {{ agency.longitude }}, {{ agency.id }})" style="cursor: pointer; z-index: 1000">
... // rest of the html code

As my backend runs on Django, I utilize {{}}s.

In the moveMap() function, I pass the agency.latitude, agency.longitude, and agency.id. Here's the corresponding JavaScript code:

function moveMap(lat, long, id) {
    map.flyTo([lat, long], 14, {
      animate: true,
      duration: 3.5,
    });
    openPopupByID(id);
}

After moving the map to the correct marker location, the openPopupById() function is called with the id as a parameter. The function implementation is as follows:

function openPopupByID(agency_id) {
    for (let item in markerList) {
        if (item["id"] === agency_id) {
            item.openPopup();
        }
    }
}

Here, I rely on markerList which is initialized as shown below:

let markerList = [];

// creating markers using coorList
for (let dataSet of coorList) {
     let latNumber = parseFloat(dataSet[0]);
     let longNumber = parseFloat(dataSet[1]);
     let marker = L.marker(L.latLng(latNumber, longNumber)).addTo(map);

     // displaying agency info in popups
     marker.bindPopup(setMarkerInfo(dataSet[2]));

     // adding each marker to the markerList
     marker["id"] = dataSet[2];
     markerList.push(marker);
}

The coorList consists of arrays containing three values: agency.latitude, agency.longitude, and agency.id indexed at 0, 1, and 2 respectively.

Therefore, I have a markerList comprising marker objects, and by assigning an id property with marker["id"] = dataSet[2];, I have included identification to the marker object. However, while trying to access the id of a marker within the openPopupByID() function, I encounter 'undefined' output from the console. Upon logging the structure of markerList with console.log(markerList), the following output is obtained: https://i.sstatic.net/jMHeN.png

This clearly shows the presence of the id property in the marker objects.

Hence, what could be causing the issue? And where did I go wrong?

Answer №1

Isn't it more advisable to utilize for..of rather than for..in?

function openPopupByID (agency_id) {
    for (let item of markerList) {
        console.log('test -- ', item.id, item);
        if (item["id"] === agency_id) {
            item.openPopup();
        }
    }
}

Answer №2

To iterate over an array, it is recommended to use the for of loop instead of the for in loop, which is more suitable for objects.

The for in loop will search for keys in the markerList array, rather than iterating through each element in the list.

source - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

function openPopupByID (agency_id) {
    for (let item of markerList) {
        if (item["id"] === agency_id) {
            item.openPopup();
        }
    }
}

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

Is there a way to eliminate an object from a multidimensional nested array in JavaScript and retrieve the parent array?

Can anyone help me figure out how to delete the "fields" object with id 47 from this nested array using JavaScript and return the entire parent array? [{ "id": 10, "name": "phone", "fields": [ { ...

Leverage the potential of the value parameter within a mongoose scope

I am currently trying to retrieve emails of a user based on their id. However, I have encountered an issue due to the asynchronous nature of the mongoose function. Mail.find({receiver_id: '#id#'}, function(err, mails) { var result = []; ...

Is Angular File API Support Compatible with HTML5?

When checking for HTML5 File API browser support in my code: private hasHtml5FileApiSupport; constructor(@Optional() @Inject(DOCUMENT) document: Document) { const w = document.defaultView; this.hasHtml5FileApiSupport = w.File && w.FileReader & ...

Dispatching identification to controller after submission

I am encountering an issue with a page that contains the following code: <div class="col-sm-2 displaybutton"> <div data-point-to="displaysHeader"> @using (Html.BeginForm("Administration", "Home", FormMethod.Post)) ...

Is submitting data through ajax giving you trouble?

As a beginner in PHP with no knowledge of Javascript, I have been relying on tutorials to complete my JS tasks. Despite trying various solutions from StackOverflow, I have yet to achieve success! My goal is to update database values by clicking the ' ...

Basic Hover Effect in Javascript

Looking at this snippet of HTML: <div id="site-header-inner"> <div id="header-logo"> <?php echo wp_get_attachment_image(get_field('header_logo','options'),'full'); ?> </div> <div id= ...

Unable to generate a file using fs.appendFile in Node.js

For some time now, I've been working on a program that is meant to save logs from a Slack team. I've managed to get most things working, but I've hit a roadblock with using fs.appendFile() successfully. The documentation states that it shoul ...

Using Laravel to remove data with an incorrect ID

Whenever I try to delete data using the Delete button, it seems like the data being deleted does not correspond to the rows I intended. Instead, the data at the top of the table gets deleted. For example, when I use return $meja, id 1 shows up instead of ...

Unable to start dat.GUI in Three.js

After running my code, I encountered an error on this line: var gui = new dat.GUI(); The error message reads: 'Unable to get the 'getItem' property null reference or undefined.' Despite importing the necessary library, I am unsure of ...

Increasing an ID number automatically using Javascript

I'm currently working on a functionality where a unique number is automatically generated whenever a new record is created. For instance, if I were to click "Create record" on a webpage, the number would auto-fill in the record ID field. Subsequently, ...

I'm having trouble with my useState in React/NEXTjs because it's not adding onto the result of a socket.io event from the server, it's simply

Frameworks used: Next.js, Socket.io, React I am currently working on a straightforward messaging application. The main concept involves emitting a message typed by a user, sending that message to the server, and then broadcasting it back to all clients th ...

Ways to resolve BuildJobExitNonZero issue on Digital Ocean

Hey everyone, this is my first time using Digital Ocean. I'm trying to deploy my app via Launch App, and my code is hosted on GitHub. However, when I try importing the code and building it, I'm encountering the following error that I don't u ...

What is the best way to display a new line when printing a string as <pre> in HTML without using ` `

I receive a text file from the PHP server that has the following content: "File version: 5\n\nstart: 1410355285955(2014/09/10 11:58:05.955)\nend: 141090402750(2014/09/10 12:00:02.750)\nUEID: 301660031\nCNC: 1181 ...

Utilize AJAX to dynamically populate a list in CodeIgniter

Currently, I am working on a project that involves using Codeigniter. One of my tasks is to populate a dropdown list from the database using Ajax. However, I encountered an error: "Uncaught SyntaxError: missing ) after argument list." Below is the code sn ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...

I desire to receive comments only once since they are being rehashed repeatedly

On the server-side: This is where I retrieve the comment from the server db.postSchema .findOne({ _id: comment.post }) .populate("owner") .exec((err, users) => { for (let i = 0; i < ...

Tips for deleting an item within a nested array object in JavaScript

Could you please advise on how to remove an object based on a condition using Javascript? If the trans cost is > 200, then keep it in obj, otherwise remove it var obj1 = [{ "id": "trans", "option": "bank", "cost": "100" }, { "id": "fund", "o ...

Dynamic computed subcomponents in Vue.js are a powerful way to create flexible

Currently, I am facing a scenario where I need to create computed local subcomponents. Specifically, I am working on custom data grid row cell components. Here is an example of what I am trying to achieve: var DataGridRow = { props: ['columns&ap ...

A guide to setting defaultValue dynamically in React Hook Form

Presently, I am facing an issue with editing the Product page. The props values are fetched through an API and sent from the parent component. However, I am struggling to set this value to my Datepicker input. This is because the defaultValue function from ...

Does the reduce method work by default like this?

const product_list=[{id:1},{id:2}] const temp_products=[{id:1,quantity:10},{id:2,quantity:20}] product_list.map(prod=>{ console.log(temp_products.reduce((init,curr_prod)=>{ return curr_prod.id == prod.id ? curr_prod.quantity : null })) ...