Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create dynamic array with jquery

I need some help regarding jquery arrays.


var queryArr;

$(markersArray).each(function(index) {

     var _locationId = index;
     var _locName    = markersArray[index].name;
     var _markerLat  = markersArray[index].marker.getLatLng().lat();
     var _markerLng  = markersArray[index].marker.getLatLng().lng();

//I DO NOT KNOW THE SYNTAX BELOW HELP IN HERE PLEASE..

      var locations = {  

        locationId:_locationId;                                
        locationName:_locName,
        lat:_markerLat,
    lng:_markerLng  }
    queryStr = { "locations": locations}    //??????????

      });


queryArr.push(location); //???????

}

I need to reach each element by using sth like this:

alert(queryArr[0].locations.locationId);

Obviously I will be using a for loop to reach each data by an index.

Can anyone give me example syntax for this.. I have found plenty examples of fixed arrays but not dynamic content.

like image 513
Ozlem Avatar asked Oct 25 '10 04:10

Ozlem


2 Answers

You're very close. The line with push needs to be moved inside the .each() loop and you need to use queryStr for the push. Make sure you don't have any other syntax errors like missing semicolons.

queryArr.push(queryStr);

Here's your example:

var queryArr = [];

$(markersArray).each(function(index) {
     var _locationId = index;
     var _locName    = markersArray[index].name;
     var _markerLat  = markersArray[index].marker.getLatLng().lat();
     var _markerLng  = markersArray[index].marker.getLatLng().lng();

     var locations = {  
        "locationId" :_locationId;                                
        "locationName" :_locName,
        "lat" :_markerLat,
        "lng" :_markerLng  
     };
     queryStr = { "locations" : locations };
     queryArr.push(queryStr);
 });
like image 120
Rebecca Chernoff Avatar answered Nov 11 '22 11:11

Rebecca Chernoff


var elements = document.getElementsByTagName("div"); // returns a nodeList
var array = jQuery.makeArray(elements );
$(array ).appendTo(document.body);

or like

var object = $('li');
var array = $.makeArray(object);
like image 33
Gadde Avatar answered Nov 11 '22 12:11

Gadde