Home > Back-end >  how to dynamically change the input values for each element inside foreach loop?
how to dynamically change the input values for each element inside foreach loop?

Time:11-24

I want to change the value of coordinates for every map element, inside the foreach loop. For example, for first map element I want to assign coordinates[0] and so on.

function initMap() {    
var coordinates = [
        {
            "lat": 123,
            "lng": 123
        },
        {
            "lat": 123,
            "lng": 123
        },
        {
            "lat": 123,
            "lng": 123
        }
  ]
var mapElements = document.querySelectorAll('.map');
mapElements.forEach((element) => {
        const uluru = { lat:coordinates[0].lat, lng:coordinates[0].lng};// how do I dynamically change values here
        console.log(uluru);
        const map = new google.maps.Map(element, {  
            zoom: 4,
            center: uluru,
        });
  const marker = new google.maps.Marker({
        position: uluru,
        map: map,
    });
});
}

CodePudding user response:

Consider this example.

function initMap() {
  var coordinates = [{
      "lat": 123,
      "lng": 123
    },
    {
      "lat": 123,
      "lng": 123
    },
    {
      "lat": 123,
      "lng": 123
    }
  ]
  var mapElements = document.querySelectorAll('.map');
  mapElements.forEach((element, index) => {
    const uluru = {
      lat: coordinates[index].lat,
      lng: coordinates[index].lng
    };
    console.log(uluru);
    const map = new google.maps.Map(element, {
      zoom: 4,
      center: uluru,
    });
    const marker = new google.maps.Marker({
      position: uluru,
      map: map,
    });
  });
}

This makes use of the index. See More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

You can also create an index variable yourself.

function initMap() {
  var coordinates = [{
      "lat": 123,
      "lng": 123
    },
    {
      "lat": 123,
      "lng": 123
    },
    {
      "lat": 123,
      "lng": 123
    }
  ]
  var mapElements = document.querySelectorAll('.map');
  var i = 0;
  mapElements.forEach((element, index) => {
    const uluru = {
      lat: coordinates[i].lat,
      lng: coordinates[i].lng
    };
    i  ;
    console.log(uluru);
    const map = new google.maps.Map(element, {
      zoom: 4,
      center: uluru,
    });
    const marker = new google.maps.Marker({
      position: uluru,
      map: map,
    });
  });
}

There are caveats to both of these since the forEach loop may have more elements than your array does.

  • Related