Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object array in jQuery

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?

like image 326
Steven Avatar asked May 03 '11 20:05

Steven


People also ask

How to get object in array jQuery?

Answer: Use the jQuery $. map() Method You can simply use the $. map() method to convert a JavaScript object to an array of items.

Are arrays objects?

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).

What is array in jQuery?

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.


2 Answers

I would use jQuery.map():

$.map(latitudes, function(lat, i) {
  return {latitude:lat, longitude:longitudes[i]};
});
like image 103
maerics Avatar answered Oct 04 '22 11:10

maerics


var coords = [];
$.each(latitudes, function(index, value) {
    coords.push({'Latitude': value, 'Longitude': longitudes[index]});
});
like image 29
Abdullah Jibaly Avatar answered Oct 04 '22 10:10

Abdullah Jibaly