如何使用lodash.js或underscore.js过滤json?

时间:2017-05-19 11:02:05

标签: javascript angularjs json underscore.js lodash

我正在尝试敲打我的头来过滤下面写的json以获得理想的结果。

[{
        "Key": "EShSOKthupE=",
        "ImageUrl": "path",
        "Title": "ABC", 
        "CityId": 16, 
        "TimezoneShortName": "PYT",
        "UtcHrsDiff": 8.5,
        "PlaceKey": "QIZHdWOa77o=",
        "PlaceName": "Shymala Hills Slums",
        "Lat": 23.2424856,
        "Long": 77.39488289999997,
        "ActivityList": [ "Test Activity" ]
      },
      {
        "Key": "NXLQpZAZT4M=",
        "ImageUrl": "",
        "Title": "ASAS",  
        "CityId": 17, 
        "TimezoneShortName": "AEST",
        "UtcHrsDiff": 10,
        "PlaceKey": "o4fAkahBzYY=",
        "PlaceName": "ASAS",
        "Lat": 12.9856503,
        "Long": 77.60569269999996,
        "ActivityList": [ "Adventure Sport" ]
      }]

现在我想使用lodash或者非核心js从json上面得到这样的json。

[{
    "PlaceKey": "QIZHdWOa77o=",
    "PlaceName": "ABC",
    "Lat": 23.2424856,
    "Long": 77.39488289999997
  },
  {
    "PlaceKey": "o4fAkahBzYY=",
    "PlaceName": "ASAS",
    "Lat": 12.9856503,
    "Long": 77.60569269999996,
  }]

我能得到什么帮助?

3 个答案:

答案 0 :(得分:6)

使用lodash:

_.map(yourArray, (el => _.pick(el, ['PlaceKey', 'PlaceName', 'Lat', 'Long'])))

答案 1 :(得分:2)

您只需在Javascript,中执行此操作,无需任何外部库,例如:

filteredArray=arr.map(function(item){
  return {
    "PlaceKey": item.PlaceKey,
    "PlaceName": item.PlaceName,
    "Lat": item.Lat,
    "Long": item.Long,
  }
})

答案 2 :(得分:1)

使用_.map功能

var finalArray = _.map(your_arr, function(obj) {
    return {
    "PlaceKey": obj.PlaceKey,
    "PlaceName": obj.PlaceName,
    "Lat": obj.Lat,
    "Long": obj.Long,
  }
});

或只使用数组map函数:

var finalArray = your_arr.map(function(obj) {
   return {
     "PlaceKey": obj.PlaceKey,
     "PlaceName": obj.PlaceName,
     "Lat": obj.Lat,
     "Long": obj.Long,
   }
});