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?
Answer: Use the jQuery $. map() Method You can simply use the $. map() method to convert a JavaScript object to an array of items.
In the Java programming language, arrays are objects (§4.3. 1), are dynamically created, and may be assigned to variables of type Object (§4.3. 2).
each function to iterate over elements of arrays, as well as properties of objects. The jquery . each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
I 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]});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With