简体   繁体   中英

How to get values associated to a javascript dictionary

I have this declared dictionary variable inside a script tag in a html page. I would like to get the values associated to the "Roads" and "Intersections" keys. Theses values change every time the page is refreshed. Catching them, will allow me to change these colors on my python folium map using Javascript :

(geo_json_cae0ea33c63e4c438678d293e5c32c0d.setStyle({'fillColor': "#FF0000", 'color': "#FF0000"});

Following suggestions, I tried this but I couldn't have the expected result.

var layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb = {
            base_layers : {
            },
            overlays :  {
                "Roads" : geo_json_cae0ea33c63e4c438678d293e5c32c0d,
                "Intersections" : feature_group_1c28eff59e394734be54cf676a09eae1,
            },
        };


window.onload = function() {
  for (var name in this) {
    if (name.includes("layer_control_")) {
      for(let key in this[name]) {
        console.log(key, this[name][key])
        
      }
    }
  }

};

I got lots of things in the console except what I want (the values of overlays dictionary)

Assuming that you can't access layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb directly (because the name changes on reload), you can access the variable from within window :

 var layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb = { base_layers : { }, overlays : { "Roads" : "geo_json_cae0ea33c63e4c438678d293e5c32c0d", "Intersections" : "feature_group_1c28eff59e394734be54cf676a09eae1", }, }; window.onload = function(){ for (const name in this){ if (name.includes("layer_control_")){ let { Roads, Intersections } = window[name].overlays; console.log(Roads, Intersections); // Roads.setStyle({'fillColor': "#FF0000", 'color': "#FF0000"}); // ... } } };

Your initial approach with for (var name in this) was correct.
However, name only contains the name (string) of the variable, and not it's value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM