最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Creating an object array in jQuery - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 7

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]});
});

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.

发布评论

评论列表(0)

  1. 暂无评论