添加数组元素到现有的javascript数组

adding array elements to existing javascript array

本文关键字:javascript 数组 数组元素 添加      更新时间:2023-09-26

我想从两个来源读取地理数据(经度/纬度)到一个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 ]
我希望我说的很清楚。

我要创建一个对象的对象。

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 }
}