从数组中删除JSON中不存在的项

时间:2018-05-05 17:27:51

标签: jquery json google-maps

我得到了JSON数据:

[
  {"id":'1029',
    "position":
        {
        "lat":'40.690902',
        "long":'-73.993449'
        }
  }
]

然后处理数据并将每个标记添加到myMarkers并创建标记,或者如果它已经存在,则更新地图上的位置:

// Remember markers
var myMarkers = {};

***// Code removed here which gets JSON via ajax //***

// Move data to res variable, just for fun..
var res = data;

// Process the data..
for(var i=0, len=res.length; i<len; i++) {

    // Does this marker exist?
    if(myMarkers.hasOwnProperty(res[i].id)) {

        // Update position
        myMarkers[res[i].id].setPosition(new google.maps.LatLng(res[i].position.lat,res[i].position.long));

    } else {
    // It does NOT exist, create it ..

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(res[i].position.lat,res[i].position.long),
            map:map,
        });    

        myMarkers[res[i].id] = marker;

    }   

}

到目前为止,这么好。现在,我遇到了JSON数据可能缺少某些先前创建并已在地图上的项目的问题。在这种情况下,我希望它们从myMarkers中完全删除并从地图中删除。我无法理解如何实现这一目标。有什么建议吗?

更新:

我尝试了以下内容以及#34;反向&#34;这个过程但它似乎没有效果,即使它对我有意义(至少对我来说):

for(var i=0, len=myMarkers.length; i<len; i++) {
                console.log("Checking reverse..");

                    //Do we have this marker already?
                    if(data.hasOwnProperty(res[i].id)) {

                        console.log(res[i].id+" exists ..");
                        // Remove it here..

                    } else {

                        console.log(res[i].id+" does NOT exist ..");
                        // Do nothing

                    }


                }

我确信我只是有点不对劲,但我无法弄清楚在哪里。

1 个答案:

答案 0 :(得分:1)

我创建了一个示例代码段,展示了如何从myMarkers对象中删除JSON数组中不存在的标记dataJSON

&#13;
&#13;
let dataJSON = [
  {
  	"id":'1',
    "position":
        {
        "lat":'40.690902',
        "long":'-73.993449'
        }
  },
  {
  	"id":'3',
    "position":
        {
        "lat":'40.690902',
        "long":'-74.993449'
        }
  },
  {
  	"id":'5',
    "position":
        {
        "lat":'41.690902',
        "long":'-73.993449'
        }
  }
];

let myMarkers = {
	'1': new Object(),
  '2': new Object(),
  '3': new Object(),
  '4': new Object(),
  '5': new Object()
};

let idsFromJSON = dataJSON.map(jsonElem => jsonElem.id);
console.log("IDs from JSON");
console.log(idsFromJSON);

let idsFromMarkers = Object.getOwnPropertyNames(myMarkers);
console.log("IDs from myMarkers");
console.log(idsFromMarkers);

let jsonSet = new Set(idsFromJSON);
let markersSet = new Set(idsFromMarkers);

let difference = new Set(
    [...markersSet].filter(x => !jsonSet.has(x)));

difference.forEach(id => {
		//First you should delete marker from map
    //myMarkers[id].setMap(null);  //commented as we don't have real instances in this example
    //Now delete marker from hash
    delete myMarkers[id];
});

console.log("Markers after delete");
console.log(myMarkers);
&#13;
&#13;
&#13;

我希望这有帮助!