1

I am using WordPress and in JS I have multiple instances of this, I am passing data from PHP to JS

<script type='text/javascript'>
/* <![CDATA[ */
var googlemaps_165 = {"markers":[[....]],"zoom":""};
var googlemaps_169 = {"markers":[[....]],"zoom":""};
/* ]]> */
</script>

In HTML I have this

<div class="wpmaps wpmaps--165" data-id="googlemaps_165"></div>
<div class="wpmaps wpmaps--169" data-id="googlemaps_169"></div>

In JS I could work with data manually like this

var markers = googlemaps_165.markers

But how can I do this dynamically?

var wpmaps = document.querySelectorAll('.wpmaps');

for (var i = 0; i < wpmaps.length; ++i) {

    // this gives me "googlemaps_165" which is correct
    var dataName = wpmaps[i].getAttribute('data-id');

    // But I can't do this since dataName in this case is only a name, I can't access it this way
    var markers = dataName.markers;

}
Ivan Topić
  • 3,064
  • 6
  • 34
  • 47

1 Answers1

3

Global variables are properties of the window object, and you can access them dynamically using the brackets ([]) notation:

var wpmaps = document.querySelectorAll('.wpmaps');

for (var i = 0; i < wpmaps.length; ++i) {

  // this gives me "googlemaps_165" which is correct
  var dataName = wpmaps[i].getAttribute('data-id');

  // But I can't do this since dataName in this case is only a name, I can't access it this way
  var markers = window[dataName].markers;

  console.log(markers);
}
<script type='text/javascript'>
  /* <![CDATA[ */
  var googlemaps_165 = {
    "markers": [
      [1]
    ],
    "zoom": ""
  };
  var googlemaps_169 = {
    "markers": [
      [2]
    ],
    "zoom": ""
  };
  /* ]]> */
</script>
In HTML I have this

<div class="wpmaps wpmaps--165" data-id="googlemaps_165"></div>
<div class="wpmaps wpmaps--169" data-id="googlemaps_169"></div>

You can also use NodeList.forEach() to iterate the nodes instead of the for loop, and access the data-id via the elements dataset:

document.querySelectorAll('.wpmaps')
  .forEach(function(wpmap) {
    var dataName = wpmap.dataset.id;
    
    var markers = window[dataName].markers;
    
    console.log(markers);
  });
<script type='text/javascript'>
  /* <![CDATA[ */
  var googlemaps_165 = {
    "markers": [
      [1]
    ],
    "zoom": ""
  };
  var googlemaps_169 = {
    "markers": [
      [2]
    ],
    "zoom": ""
  };
  /* ]]> */
</script>
In HTML I have this

<div class="wpmaps wpmaps--165" data-id="googlemaps_165"></div>
<div class="wpmaps wpmaps--169" data-id="googlemaps_169"></div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209