使用Lodash Library提取密钥对

时间:2016-01-05 16:44:47

标签: json lodash

我有JSON对象

{  
   "data":[  
      {  
         "customer":101,
         "profile":7,
         "context":{  
            "rows":20,
            "from":"2016-01-05T06:14:02.750Z",
            "filter_group_id":null,
            "order":"desc",
            "q":"host",
            "start":0,
            "source_group_id":null,
            "hi":"",
            "filters":[  

            ],
            "terms":"host",
            "source_group_name":null,
            "until":"2016-01-05T07:14:02.750Z"
         },
         "search_type":"searchui",
         "search_time":"2016-01-05 13:33:01",
         "id":724
      },
      {  
         "customer":101,
         "profile":7,
         "context":{  
            "rows":20,
            "from":"2016-01-05T06:14:02.750Z",
            "filter_group_id":null,
            "order":"desc",
            "q":"host",
            "start":0,
            "source_group_id":null,
            "hi":"",
            "filters":[  

            ],
            "terms":"host",
            "source_group_name":null,
            "until":"2016-01-05T07:14:02.750Z"
         },
         "search_type":"searchui",
         "search_time":"2016-01-05 13:26:42",
         "id":723
      }
   ]
}

我想使用lodash从上面的json数据中提取键值对。

我是新手lodash libray用户。我读到了_.map,_.any但是无法按要求实现。

预期的JSON对象:

[
    {
        "id":724
        "search_time":"2016-01-05 13:33:01",
        "filters":[],
        "from":"2016-01-05T06:14:02.750Z",
        "until":"2016-01-05T07:14:02.750Z"
        "terms":"host",
        "source_group_name":null,
    },
    {
        "id":723
        "search_time":"2016-01-05 13:26:42",
        "filters":[],
        "from":"2016-01-05T06:14:02.750Z",
        "until":"2016-01-05T07:14:02.750Z",
        "terms":"host",
        "source_group_name":null,
    }
]

2 个答案:

答案 0 :(得分:0)

应该是这样的:

var newArray = [];
_.each(data, function(item){
    newArray.push({
       "id":item.id
        "search_time":item.search_time,
        "filters":context.filters,
        ...etc...
    });
});

答案 1 :(得分:0)

我不知道它是否是更具性能的方式,但我认为它有效。

 var dataFilter = _.map(data, function(value){
    return _.merge(
          _.pick(value.context, 'filters', 'from', 'until', 'terms', 'source_group_name'),
          _.pick(value, 'id', 'search_time')
    );
 });