2011-12-28 72 views
1

我想从两个源地理数据(经度/纬度)读入一个Javascript数组。我创建了一个JavaScript对象与数组来保存这些数据向现有的javascript数组添加数组元素

这是我的对象定义:

var GeoObject = { 
    "info": [ ] 
}; 

当读取数据的两个来源,如果该键的recordId在数组中已经存在,则追加新数组元素(lat & lon)添加到现有的GeoObject,否则添加一个新的数组记录。

例如,如果的recordId 99999已不存在,则添加阵列(像SQL添加)

GeoObject.info.push( 
{ "RecordId": "99999" , "Bing_long": -75.0000, "Bing_lat": 41.0000 }) 

如果记录99999已经存在,则新的数据添加到现有的阵列(像SQL更新) 。

GeoObject.info.update???( 
{ "RecordId": "99999" , "Google_long": -75.0001, "Google_lat": 41.0001 }) 

当应用程序结束时,对象中的每个数组应包含五个数组元素,包括RecordId。例如:

[ "RecordId": "88888" , "Bing_long": -74.0000, "Bing_lat": 40.0001, "Google_long": -74.0001, "Bing_long": -70.0001 ] 
[ "RecordId": "99999" , "Bing_long": -75.0000, "Bing_lat": 41.0001, "Google_long": -75.0001, "Bing_long": -75.0001 ] 

我希望我很清楚。这对我来说很新而且有点复杂。

也许对象定义对于这种情况并不理想。

+1

也许,使其在格式:'[ info:{recordId1 => {data1},recordId2 => {data2}}]',“push or update”就是'info [recId] = blahblah'。为了保持当前的格式,每次都需要一个辅助DS或迭代(过滤或变异),这不一定是错误的。 – 2011-12-28 03:23:40

回答

1

我会做一个对象的对象。

var GeoObject = { 
    // empty 
} 

function addRecords(idAsAString, records) { 
    if (GeoObject[idAsAString] === undefined) { 
    GeoObject[idAsAString] = records; 
    } else { 
    for (var i in records) { 
     GeoObject[idAsAString][i] = records[i]; 
    } 
    } 
} 

// makes a new 
addRecords('9990', { "Bing_long": -75.0000, "Bing_lat": 41.0000 }); 
//updates:  
addRecords('9990', { "Google_long": -75.0001, "Google_lat": 41.0001 }); 

这给你的对象,看起来像这样:

GeoObject = { '9990' : { "Bing_long": -75.0000, 
         "Bing_lat": 41.0000, 
         "Google_long": -75.0001, 
         "Google_lat": 41.0001 } 
} 

有了第二个记录就应该是这样的:

GeoObject = { '9990' : { "Bing_long": -75.0000, 
         "Bing_lat": 41.0000, 
         "Google_long": -75.0001, 
         "Google_lat": 41.0001 }, 

       '1212' : { "Bing_long": -35.0000, 
         "Bing_lat": 21.0000 } 
} 
+0

优秀的答案! – 2011-12-28 12:53:40