'leaflet L.Control Overlay

As a newcomer to javascript and the use of leaflet I'm unsure which subject this should be. Using the Layer Groups and Layers Control example as a model I wish to assign the Control text to the overlays from a variable. Inserting the variable name simply uses that as text. Code I've used follows.

    var cities_title_0="cities(N-S)"
    var cities_title_1="cities(E-W)"
    var overlays    =   {cities_title_0: cities_layer[0],cities_title_1: cities_layer[1] };
    L.control.layers(null,overlays).addTo(map);

How can I get the value of the variable in the control and not it's name please?



Solution 1:[1]

Previously (<= ES5) you would have to proceed in 2 steps:

  1. Initialize the object var overlays = {}
  2. Assign your computed key: overlays[cities_title_0] = cities_layer[0]

Solution 2:[2]

One way is to put the variable name in [] - eg

var cities_title_0="cities(N-S)"
var cities_title_1="cities(E-W)"
var overlays    =   {[cities_title_0]: cities_layer[0], [cities_title_1]: cities_layer[1] };
L.control.layers(null,overlays).addTo(map);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ghybs
Solution 2 peeebeee