【问题标题】:Javascript - Filter geojson based on other json's valuesJavascript - 根据其他 json 的值过滤 geojson
【发布时间】:2019-06-02 13:03:48
【问题描述】:

我正在努力根据另一个 JSON 的值过滤 geojson。具体来说,我正在尝试根据另一个 json 中的 id 过滤 geojson。每次,我过滤的 geojson 都返回 null。

我创建了一个 JSfiddle here 显示我正在尝试做的事情。

代码是

    mygeojson={crs: {properties: {name: "EPSG:4326"}, type: "name"},
features: [
    {geometry: {coordinates: [25, 37], type: "Point"},properties: {"wineryid":3},type:"Feature"},
  {geometry: {coordinates: [26, 37], type: "Point"},properties: {"wineryid":45},type:"Feature"},
  {geometry: {coordinates: [25, 38], type: "Point"},properties: {"wineryid":34},type:"Feature"},
  {geometry: {coordinates: [28, 37], type: "Point"},properties: {"wineryid":42},type:"Feature"},
  {geometry: {coordinates: [25, 342], type: "Point"},properties: {"wineryid":80},type:"Feature"},
  {geometry: {coordinates: [25.24, 37.12], type: "Point"},properties: {"wineryid":120},type:"Feature"}], type:"FeatureCollection"};
mylist=[{id:1, name:"test1"},{id:34,name:"test2"}];
tempgeojson = mygeojson.features.filter(function (item) {
  return (mylist.every(f => item.properties.id === f.id) )
});
filteredgeojson={};
filteredgeojson.features=tempgeojson;
filteredgeojson.crs=mygeojson.crs;
filteredgeojson.type="FeatureCollection";

我怎样才能得到我需要的过滤geojson? (在这个例子中,预期的 geojson 大约是 id 的 1 和 34。)

【问题讨论】:

    标签: javascript json filter geojson


    【解决方案1】:

    尝试以下代码进行特征过滤

    filteredgeojson.features = mygeojson.features.filter(item => { 
         if(mylist.filter(myitem => myitem.id === item.properties.wineryid).length > 0) { 
              return item;
          }
    });
    

    【讨论】:

    • 很好的答案!简单,简短,而且运行速度很快。接受并感谢!
    猜你喜欢
    • 2020-12-22
    • 1970-01-01
    • 2019-03-15
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    相关资源
    最近更新 更多