2011-12-28 73 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