Creating an array of objects in jQuery

I want to store an array of latitudes / longitudes. I have this data on my page:

<input type="hidden" class="latitude" value="-12.3456" /> <input type="hidden" class="longitude" value="12.3456" /> <input type="hidden" class="latitude" value="98.7654" /> <input type="hidden" class="longitude" value="-98.7654" /> 

And I put them in arrays as follows:

 var latitudes = $('.latitude').map(function () { return this.value; }).get(); var longitudes = $('.longitude').map(function () { return this.value; }).get(); 

But I think it would be better to store them in one array as objects, so that I can say:

 $.each(array, function (i, obj) { alert(obj.Latitude); alert(obj.Longitude); }); 

How can I change this to create an array of objects?

+6
source share
3 answers

I would use jQuery.map () :

 $.map(latitudes, function(lat, i) { return {latitude:lat, longitude:longitudes[i]}; }); 
+6
source
 var coords = []; $.each(latitudes, function(index, value) { coords.push({'Latitude': value, 'Longitude': longitudes[index]}); }); 
+2
source

This is one way:

http://jsfiddle.net/95cga/

 var longs=$(".longitude"); var lats=$(".latitude"); var objs=[]; for(var i=0;i<Math.min(longs.length,lats.length);i++){ var obj={ "Latitude" : longs.eq(i).val(), "Longitude" : lats.eq(i).val() } objs.push(obj); } 

I do not like to assume that things are always in matching pairs, even if they should be. That is why Math.min is.

0
source

Source: https://habr.com/ru/post/887230/


All Articles