基于唯一ID合并geojson

Merge geojson based on unique ID

本文关键字:ID 合并 geojson 唯一 于唯一      更新时间:2023-09-26

我是Javascript的初学者,所以请提出这个可能很愚蠢的问题。我想根据唯一的对象id合并两个json文件。

第一个看起来像这样:

"features": [{
      "id": "3876802",
      "properties": {
        "name": "some name",
        "facts": "some facts"}},
      {"id": "3876803",
      "properties": {"name":"another name"...}}...]

第二个是这样的:

"features": [{
          "id": "3876803",
          "properties": {
          "description": "some description", 
          "website": "afancywebsite"}},
         {"id": "3876803",
          "properties": {...}}]

第二个Json中的元素顺序不同,并且第一个文件中的所有元素都不在第二个文件中。

结果应该是这样的:

"features": [{
          "id": "3876802",
          "properties": {
            "name": "some name",
            "facts": "some facts"}},{
          "id": "3876803",
          "properties": {
            "name":"another name",
            "description": "some description", 
            "website": "afancywebsite"}}]

我开始编码这个,但我不知道如何让它工作。。。

 for(var i in json1.features){
        for (var z in json2.features){
        if (json1.features[i].id===json2.features[z].id){
            json1.feature[i].properties = json2.features[z].properties}}}

这将完成任务:

    var features =  [
    {"id": "3876802",
        "properties": {
            "name": "some name",
            "facts": "some facts"}
    },
    {"id": "3876803",
        "properties": {
            "name":"another name"
        }
    }
    ];

    var features2 = [{
        "id": "3876803",
        "properties": {
            "description": "some description", 
            "website": "afancywebsite"
            }
        }
    ];

features.map(function(feature){
    var matchedArray = features2.filter(function(feature2){
        return feature2.id === feature.id;
    });
    if(matchedArray && matchedArray[0]){
        for(var attr in matchedArray[0].properties){
            feature.properties[attr] = matchedArray[0].properties[attr];
        }
    }
});

我们首先使用Array.map()逐个运行features数组。

然后,我们对features2数组使用Array.filter(),这为我们提供了一个数组,其中包含features2(match[0])中唯一一个与feature.id具有相同id的对象。

如果匹配,那么我们使用"for in"循环遍历features2对象中的"properties",并将它们复制到"feature"对象。


如果您想获得有关这方面的高级信息,请查看这个stackerflow问题:如何动态合并两个JavaScript对象的属性?。例如,如果您正在编写防弹javascript,则应该在For in循环中使用"hasOwnProperty"。您可能还希望防止"features2"中的属性覆盖"features"中同名的属性。


然而,如果你想让你的代码或多或少保持原样,这也可以:

for(var i in features){
    for (var z in features2){
        if (features[i].id===features2[z].id){
            for(var attr in features2[z].properties){
                features[i].properties[attr] = features2[z].properties[attr];
            }
        }
    }
}