I want to store an array of latitudes/longitudes. I have these inputs 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'm putting them into arrays like so:
var latitudes = $('.latitude').map(function () { return this.value; }).get();
var longitudes = $('.longitude').map(function () { return this.value; }).get();
But I'm thinking that it would be better to store them in a single array as objects, so that I can say:
$.each(array, function (i, obj) {
alert(obj.Latitude);
alert(obj.Longitude);
});
How can I modify this to create an array of objects?
I want to store an array of latitudes/longitudes. I have these inputs 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'm putting them into arrays like so:
var latitudes = $('.latitude').map(function () { return this.value; }).get();
var longitudes = $('.longitude').map(function () { return this.value; }).get();
But I'm thinking that it would be better to store them in a single array as objects, so that I can say:
$.each(array, function (i, obj) {
alert(obj.Latitude);
alert(obj.Longitude);
});
How can I modify this to create an array of objects?
Share Improve this question asked May 3, 2011 at 20:07 StevenSteven 18.9k74 gold badges203 silver badges302 bronze badges3 Answers
Reset to default 7I would use jQuery.map():
$.map(latitudes, function(lat, i) {
return {latitude:lat, longitude:longitudes[i]};
});
var coords = [];
$.each(latitudes, function(index, value) {
coords.push({'Latitude': value, 'Longitude': longitudes[index]});
});
This is one way:
http://jsfiddle/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 don't like to assume things are always in matching pairs, even if they should be. That's why the Math.min is there.