Using JavaScript to Create Dynamic Variable Names - Multiple Arrays?

In my project, I am working on creating markers for each user in my loop. These markers need to be generated in a way that allows me to later select them based on the corresponding userId.

$.each($.parseJSON(window.usersArray), function (i, user) {
    window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
    console.log(window.userMarkers[user['id']]);
});

AFTER UPDATE

Unfortunately, during this process, I encountered the following error message:

Cannot set property '3' of undefined
, with '3' referring to the specific user's ID.

Answer №1

First, it's essential to initialize the object (or array) before populating it with any values.

const userMarkers = {};

$.each($.parseJSON(window.usersArray), function(index, userData) {
    userMarkers[userData['id']] = L.marker(98.76, 12.34).addTo(map);
    console.log(userMarkers[userData['id']]);
});

Answer №2

Tip: Make sure to declare the array before assigning values to it! For instance:

window.userMarkers = [];

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

AutoComplete feature activates when I choose a suggestion from the dropdown menu

<Autocomplete disablePortal id="geo-select-country" options={all_country} defaultValue={nation} onChange={(event, selected_nation) => { set_nation(selected_nation); }} ...

Step-by-step guide for sending data using module.exports in a node.js application

Currently, I am working on implementing a feature that will allow users to input data and store it in a database collection. The technologies I am using for this project are Node.js, MongoDB, Mongoose, Express.js, and AJAX. My goal is to capture user inpu ...

Using CSS to position an element relative/absolute within text inline

Need help aligning caret icons next to dynamically populated text in a navbar menu with dropdown tabs at any viewport size. Referring to positioning similar to the green carets shown here: https://i.stack.imgur.com/4XM7x.png Check out the code snippet bel ...

Notifying with Socket.IO in Node.js

Hey there, I'm currently working on implementing a notification system but have hit a roadblock. I've sent an invitation to a user to join the club. socket.on("notify", async (message) => { // invite the user John Doe io.to('socke ...

Unable to reset session with JavaScript on JSP page

Created a session from the login.jsp page using a servlet String msg = ""; HttpSession sess = request.getSession(); // if(sess != null) //sess.invalidate(); if (sess.getId() != null) { sess.setAttribute("uname", ...

JSON array cannot be traversed

I am retrieving an array from my API response in NODEJS: res.json(friends) [ { "id": 7795239, "username": "janesmith" }, { "id": 1363327, "username": "johnsmith" } ] However, I am encountering difficulties ...

Text field auto-saving within an iFrame using localStorage is not functioning as expected

My goal is to create a rich text editor with an autosave feature using an iframe. Although each code part works individually, I am struggling to combine them effectively. View LIVEDEMO This graphic illustrates what I aim to accomplish: The editable iFram ...

Tips for organizing a multi-dimensional array based on various column indexes

I am looking to organize a multidimensional array by multiple column index. Take, for instance, the test data provided below: var source = [ ["Jack","A","B1", 4], ["AVicky","M", "B2", 2], [ ...

How can one pass req.validationErrors() from the backend to the frontend with Express Validator?

Hello and thank you for taking the time to read this. I am currently trying to implement express-validator in my project. It's working well as it blocks posts if, for example, the name input is empty. However, I'm struggling to display the error ...

Continuously examine whether all elements within a multi-layered array of unknown depth are void

I am facing an issue with determining if all the values in a multidimensional array posted to my PHP script are empty or not. Below is the array structure: $array = [ [ 'a' => '', 'b' => [ ...

The import failed because 'behavior' is not being exported from 'd3'

I've been experimenting with creating a sankey diagram using d3 and react.js, and I'm using this example as a guide. I am new to React (just 2 days in) and encountering an error that says: ./src/components/SankeyComponent.js An import error occ ...

A guide on getting the `Message` return from `CommandInteraction.reply()` in the discord API

In my TypeScript code snippet, I am generating an embed in response to user interaction and sending it. Here is the code: const embed = await this.generateEmbed(...); await interaction.reply({embeds: [embed]}); const sentMessage: Message = <Message<b ...

"Developing a JSON object from a Form: A Step-by-

Currently utilizing the Drag n Drop FormBuilder for form creation. My objective is to generate a JSON representation of the form as shown below: { "action":"hello.html", "method":"get", "enctype":"multipart/form-data", "html":[ { ...

Does element.click() in Protractor's Webdriver method return a promise, or is there a way for it to handle errors?

Is the element(by.css()).click() method returning a promise, or is there a way to catch and assert against any errors that may occur? In my scenario, I have a component that is not clickable, and I want to handle the error when this happens. I also want t ...

Traverse Through multiple strings in double pointer of characters

Looking at a function with the signature below: void foo (char **bar); The 'bar' variable represents an array of strings without a specified length. I am faced with the challenge of writing a loop to check if each string in 'bar' mee ...

Arrange array of objects with unspecified and non-existent values

Is there a way to sort an array of objects in JavaScript that contains null and undefined values? The goal is to display items with a "jobTitle" property first, sorted by rating, followed by items without a "jobTitle" also sorted by rating. Sample Data: d ...

There seems to be a problem with the JavaScript on this page - it could be running slowly or may have become unresponsive

Recently, I incorporated several jQuery components into my website and all was running smoothly. However, out of the blue, an error message started popping up: "A script on this page may be busy, or it may have stopped responding. You can stop the script ...

Is there a way to retrieve JSON data from a child component and pass it to a parent component in Vue.js?

I have data from the results stored in a child component that needs to be passed to the main component. The Main Component is the parent, so whenever I click the button, the results should be collected in the main app <button @click="showFinalResu ...

The value of Express session within the callback is not retained when accessed outside

I'm encountering an issue with my Express route setup. Here's the current code snippet: app.get("/route", function(req, res){ if (someBoolean){ someFunction(stuff, function(user){ ... req.session.user = user; ...

An alternative method to confirm the checkbox selection without physically clicking on it

Currently, I'm in the process of creating a basic to-do list and have been attempting to connect the task with its corresponding checkbox. My goal is for the checkbox to automatically be checked when the task is clicked. Instead of using HTML to add ...