6

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?

3 Answers 3

7

I would use jQuery.map():

$.map(latitudes, function(lat, i) {
  return {latitude:lat, longitude:longitudes[i]};
});
Sign up to request clarification or add additional context in comments.

1 Comment

Nice to know jQuery has a map function!
2
var coords = [];
$.each(latitudes, function(index, value) {
    coords.push({'Latitude': value, 'Longitude': longitudes[index]});
});

Comments

0

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 don't like to assume things are always in matching pairs, even if they should be. That's why the Math.min is there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.