How to add variable to array [JS]

2

I have the following code:

var newLat = markerElem.getAttribute('lat');
var newLng = markerElem.getAttribute('lng');

var locations = [
    {lat: newLat, lng: newLng}
]

I want to get the values of the variables newLat and newLng and store them within the locations array as values of their respective indexes.

EXAMPLE

I want the values of the variables newLat and newLng to be passed to the indexes of array lat and lng , thus:

var newLat = 123;
var newLng = 321;

var locations = [
    {lat: 123, lng: 321}
]
    
asked by anonymous 29.06.2018 / 15:55

2 answers

2

If your wish is to add to the array do

locations.push({ lat: newLat , lng: newLng});

The javascript will add a new index in your array and then to retrieve it just go through it.

    
29.06.2018 / 22:26
3

You can change the values this way:

var locations = [
    {lat: '', lng: ''}
]

var markerElem = document.getElementById("div");
var newLat = markerElem.getAttribute('lat');
var newLng = markerElem.getAttribute('lng');

locations[0].lat = newLat; // altera lat
locations[0].lng = newLng; // altera lng

console.log(locations);
<div id="div" lat="123" lng="456"></div>

locations[0] selects the first array index.

If you want to add a new index to the array, you can do this:

var locations = [];

var markerElem = document.getElementById("div");
var lat = markerElem.getAttribute('lat');
var lng = markerElem.getAttribute('lng');

locations.push({ lat , lng });

console.log(locations);
<div id="div" lat="123" lng="456"></div>
  

Placing just the name of the variable, the name and value are already added   of the variable as the object's key in the array.

    
29.06.2018 / 16:05