使用underscore.js按年过滤

时间:2016-08-17 16:52:51

标签: javascript underscore.js leaflet

我有一张传单互动地图,我希望按年过滤掉geojson数据。我想使用underscore.js进行过滤。有问题的字段是" info_city",其中包含年份条目。我的过滤功能如下:

function filterByYear(data){
    console.log("filtering")
    console.log(data)
    f = _.where(data, {info_date : "2006"}); 
    console.log(f) 
    return f;
}

以下是我的geojson的设置方式:

{
  "type": "Feature",
  "properties": {
    "info_address": "Insitut fur Rontgendiagnostik, Universitatsklinikum Wurzburg, Oberdurrbacher Str 6",
    "info_city": "Wuerzburg",
    "info_state": "Germany",
    "info_zip": 97080,
    "info_country": "",
    "info_notes": "Unsure of how to format the German address",
    "info_lastName": "Bley",
    "info_maidenName": "",
    "info_firstName": "Thorsten",
    "info_middleName": "",
    "info_intern": "",
    "info_resident": "",
    "info_fellow": "",
    "info_fellowshipSection": "",
    "info_honoraryFellow": "",
    "info_formerFaculty": "fac",
    "info_facultySection": "Thoracic Imaging",
    "info_residencyBegin": "",
    "info_residencyEnd": "",
    "info_fellowshipBegin": "",
    "info_fellowshipEnd": "",
    "info_institution": "",
    "info_position": "Visiting faculty",
    "info_count": 1,
    "info_resDate": 1900,
    "info_felDate": 1900,
    "info_date": 2009,
    "info_status": "fac"
  },

underscore.js应自动读取" info_date"作为一个领域?或者,我是否需要做一些准备并将info_date字段隔离为变量?任何帮助赞赏。

5 个答案:

答案 0 :(得分:1)

info_date是一个数字,而不是一个字符串 变化

f = _.where(data, {info_date : "2006"}); 

通过

f = _.where(data, {info_date : 2006}); 

答案 1 :(得分:0)

您可以使用以下内容:

f = _.filter(data, o => _.isMatch(o.properties, {info_date : 2009}))

这样,{info_date : 2009}可以扩展到任何想要匹配的json对象。

答案 2 :(得分:0)

您的数据嵌套在data.properties中,因此_.where无法找到它。你的GeoJSON数据结构缺少一个左大括号,所以我不能100%确定我知道你的结构,但它看起来像你可以简单地说:

_.filter(data, function(d) { return d.properties.info_date == 2006; });

答案 3 :(得分:0)

非常感谢您的建议我尝试了以下内容,但我仍然无法控制日志(f)并获得任何显示内容。

function filterByYear(data){
console.log("filtering")
console.log(data)
f = _.filter(data, function(d) { return d.properties.info_date == 2014; });
console.log(f)
return f;

}

答案 4 :(得分:0)

您可以使用filter function使用普通javascript执行相同的操作,如果数据是数组则不使用下划线

f = data.filter(function(d){ return d.properties.info_date === '2016';})

filter函数的返回值又是一个数组。要获得第一个元素,你可以做到

f = data.filter(function(d){ return d.properties.info_date === '2016';})[0];