Matching a string with a variable in JavaScript: A simple guide

Can you assist me?

I am trying to have activeLayers = [bus,stops,slot1] instead of

activeLayers = ["bus","stops","slot1"]
. How can I achieve this? Essentially, I want to convert the string into the object it references.

Unfortunately, my current approach is not working. Here is some additional code that may provide more context:

window.onload = function () {
                var validLayers = {
                    slot1 : new L.LayerGroup(),
                    places : new L.LayerGroup(),
                    stops : new L.LayerGroup()
                    };
                    var platz = L.MakiMarkers.icon({icon: "embassy", color: "#f00", size: "l"});
                    var extern = L.MakiMarkers.icon({icon: "college", color: "#FF9900", size: "l"});


                        // Important Places
                        L.marker([49.99264845,8.24160625696918], {icon: platz}).bindPopup('Wiese vor dem ZDV').addTo(validLayers.places);
                        L.marker([49.99454,8.24384], {icon: platz}).bindPopup('Rote Infobox').addTo(validLayers.places);
                        L.marker([49.99182355,8.23384953468164],{icon:platz}).bindPopup('Zentralmensa').addTo(validLayers.places);

// Get url parameters
var params = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
    params[key] = value;
});


if( params.layers) {
    var activeLayers = (function(arr) {
        var l = arr.length, i, ret = {};
        for( i=0; i<l; i++) ret[i] = validLayers[arr[i]];
        return ret;
    })(params.layers.split(","));
}

// Create map
var map = new L.Map('map', {
    center: [params.lat || 49.99238, params.lng || 8.23779],
    minZoom: 12,
    maxZoom: 18,
    zoom: params.zoom || 15,
    layers: activeLayers || [validLayers.places, validLayers.stops ,validLayers.slot1]
});



                var baseLayers = {
                };

                var overlays = {
                    "Other": validLayers.places,
                    "Bus": validLayers.stops,
                    "Slot 1": validLayers.slot1,
                    "Slot 2": validLayers.slot2,
                    "Slot 3": validLayers.slot3,
                    "Slot 4": validLayers.slot4
                };



                L.control.layers(baseLayers, overlays).addTo(map);

                L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                }).addTo(map);
}

Here is the URL I am using to display the website:

campusmap.html?lat=49.99684&lng=8.24811&zoom=18&layers=places,bus,slot1

Answer №1

Are you looking to access specific variables in the query string correctly? If that's the case, you may want to consider implementing the following solution:

const availableData = {
    number1: new L.LayerGroup(),
    locations: new L.LayerGroup(),
    destinations: new L.LayerGroup()
};

// retrieve URL parameters
// ...

if (params.data) {
    const activeData = params.data.split(",").map(function(key) {
        return availableData[key];
    });
}

In this scenario, availableData acts as a safeguard, ensuring only specified elements can be referenced.

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

Having trouble updating values in Vue3 when accessing the next item in an object?

I'm attempting to allow my users to browse through a collection of various items. Take a look at the records object below: 0: {id: 1, pipeline_id: 1, raw: '1', completion: null, processed: 0, …} 1: {id: 2, pipeline_id: 1, raw: '2&apo ...

Encountering difficulties hosting create-react-app build on shared server, receiving 404 errors specifically linked to the chunk.js file

After working smoothly with create-react-app, I encountered an issue when attempting to create a build. Following the command: npm run build The build was successfully created. However, upon downloading and uploading the build file to a shared server via ...

Ways to expand a Bootstrap input field by clicking on it:

I have successfully created a search bar in my navbar, but I am looking to add functionality that allows the input field to expand to its normal size when clicked. I believe this will require some JavaScript implementation, however, I am unsure how to proc ...

The ng-show and ng-hide directives are not working as expected, and there are no error

I'm currently working on a Todo App using AngularJS 1.x (version 1.6), but I'm having issues with ng-show and ng-hide functionality. The aim is to have a text box appear in the todo section when the edit button is clicked to modify existing todos ...

The system encountered an error while trying to access the property "slug

I am currently working on a project that involves using next.js and wordpress. I have set up my api.js file, but I encountered an issue when trying to access the [slug] property from another component. The error message displayed is "Typerror: Cannot read ...

Python Mechanize file uploading capabilities

Hey there! I've been experimenting with mechanize and Python to upload a file to a website. I've had some success so far, but now I'm facing a challenge at the upload page. I understand that mechanize doesn't support JavaScript, but I&a ...

Unveiling the method to fetch the emitted value from a child component and incorporate it into the parent component's return data in Vue

How can I retrieve the title value passed by the Topbar component and incorporate it into the data() return section? I attempted to create a method to pass the value, but was unsuccessful despite being able to successfully log the value in the parent file. ...

Setting up the propTypes for interface in React TypeScript

How can I specify the correct PropTypes for a property that is an interface in TypeScript with PropTypes? Requirements - Implementing both TS and PropTypes. Goal - To have a more precise type definition than PropTypes.any that meets standard eslint an ...

Creating subdocuments with input types in MERN stack using Apollo Sandbox and MongoDB mutations

These questions are specific to a Node server application built in JavaScript using express, apollo-server-express, mongoose, and graphql. Below is the content of the package.json file: { "name": "dimond-media-mern-app", "vers ...

Having trouble getting an AjaxBeginForm to function properly within a JQuery script on a PartialView

Within the main controller view, we bring in the partial view utilizing the following code: @Html.Partial("MapPartial", Model) Within the Partial View, I aim to display a map. Currently, there is an Ajax beginform with a submit button that ...

How can I convert a JSON template to HTML using AngularJS?

As someone who is just starting out with AngularJS, I am facing an issue where the HTML tags in a JSON file are not being encoded when rendered in HTML using AngularJS. Is there a specific method in AngularJS that can help with this? This is what my HTML ...

What Are Some Improved Techniques for Converting Error Codes to Strings?

My current project involves developing an error reporter, and I'm facing a dilemma regarding how to present error codes to users. While error codes are efficient for programmers, they can be confusing and overwhelming for end-users who are trying to t ...

Using jQuery UI Dialog with pjax for dynamic content loading

I'm currently utilizing pjax within a web application that incorporates jQuery UI dialogs. One issue I've encountered is that the div element responsible for creating the dialog gets displaced from its original container in the DOM once the dialo ...

JavaScript: Finding the current month and all subsequent months until the end of the year

Is there a way in vanilla JavaScript to retrieve the current month and the following 12 months? For instance, if today is April 2022, I would like the output to be: April 2022 May 2022 June 2022 July 2022 August 2022 September 2022 October 2022 November 2 ...

jQuery and Easy Dialog

My jQuery Model window has a form inside. Even though I have set autoOpen to false in my dialog, the fields are still visible when the page is created. All forms are contained within a div. This is what my dialog code looks like: $("#dialog-form").dial ...

The Mongoose query for the id field retrieves both the id and _id values

Within my Mongoose schema, there is a specific field named id which holds a unique identifier for each document. This operates using the same system as the standard _id field as shown below: var JobSchema = new mongoose.Schema({ id: { type:String, requi ...

What is the best way to send a query in a jQuery AJAX call?

I am a beginner in working with AJAX requests and server programming. This project is part of my school assignment. I need to include the SID that was generated as a parameter for this request. Additionally, I am trying to pass in an object of colors, a st ...

Enhancing the Efficiency of JavaScript's indexOf Method

I am currently developing a basic search algorithm in JavaScript. var title = "Discovering the Best Book of All Time"; var search1 = "of DiscoverinG boOk Best"; var search2 = "Of TIme best all" var search3 = "Book discovering time" When using indexOf(), ...

Effortlessly fill dropdown menus with data from JSON files

I've been using this jQuery code successfully, but I recently needed to add 3 more field columns to the JSON. My goal is to have the HTML select drop-downs dynamically change based on the data from the previous drop-down. Additionally, my current jQue ...

Loading a Codeigniter page from a different server

I am a beginner in the world of Codeigniter and Javascript, and I am in need of help. I want to load a page from another server using Codeigniter. What steps should I take to make this work? $("#select").change(function(){ if($('#textbox& ...