用JavaScript过滤JSON数据数组

时间:2019-09-11 06:55:38

标签: javascript arrays json

我有一个像下面的json数据

 var data =  [
    { 
      "type": "Feature", 
      "id": 1, 
      "properties": 
       {
         "name": "William", 
         "categorie": 107, 
         "laporan":"Fire",
         "time":1,
         "type": "Firefighter",
         "phone_number": "0111111" 
       }, "geometry": 
        { 
           "type": "Point", 
           "coordinates": [ 106.814893, -6.219156] 
        } 
     }
    ,
    { 
       "type": "Feature", 
       "id": 7, 
       "properties": 
        {
          "name": "John", 
          "categorie": 103, 
          "laporan":"Thief",
          "time":3,
          "type": "Police", 
          "phone_number": "0987654321" 
     }, "geometry": 
     { 
        "type": "Point", 
        "coordinates": [ 106.794107, -6.286935 ] 
     }
   }
]

我想根据时间过滤上面的json数据以获取propertiescoordinates,我尝试使用下面的代码,但是没有显示我想要的数据

  var data_filter=data.filter(function(item){
    return item.properties.time==1;         
});
console.log(data_filter)

您知道我如何过滤json数据以获取属性和协调数据吗?

谢谢

1 个答案:

答案 0 :(得分:4)

您最终可以映射所需的属性。

var data = [{ type: "Feature", id: 1, properties: { name: "William", categorie: 107, laporan: "Fire", time: 1, type: "Firefighter", phone_number: "0111111" }, geometry: { type: "Point", coordinates: [106.814893, -6.219156] } }, { type: "Feature", id: 7, properties: { name: "John", categorie: 103, laporan: "Thief", time: 3, type: "Police", phone_number: "0987654321" }, geometry: { type: "Point", coordinates: [106.794107, -6.286935] } }],
    result = data
        .filter(item => item.properties.time == 1)
        .map(({ properties, geometry: { coordinates } }) => ({ properties, coordinates }));
        
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }