Lodash:在json中获取具有多个键值匹配的新数组

时间:2016-02-24 03:59:21

标签: javascript json lodash

我已经把JSON看成是这样的

[
    {arrivalTime: "10:30 PM"
     availableSeats: 23
    boardingPoints: [{id: "3882"
    location: "abc"
    time: "02:30PM"},{id: "3882"
    location: "xyz"
    time: "02:30PM"}]
    busType: "Scania Metrolink"
    operatorName:"sham"
    commPCT: 8
    departureTime: "1:15 PM"
    droppingPoints: [{id: "3882"
    location: "dex"
    time: "02:30PM"},{id: "3882"
    location: "afg"
    time: "02:30PM"}]
    },
    {arrivalTime: "10:30 PM"
     availableSeats: 23
    boardingPoints: [{id: "3882"
    location: "def"
    time: "02:30PM"},{id: "3882"
    location: "jkl"
    time: "02:30PM"}]
    busType: "Scania "
    operatorName:"manu"
    commPCT: 8
    departureTime: "1:15 PM"
    droppingPoints: [{id: "3882"
    location: "ccd"
    time: "02:30PM"},{id: "3882"
    location: "eef"
    time: "02:30PM"}]
    }
    ]

从此我想获得与这些key值匹配的新数组。 这是钥匙。

1.BoardingPoints。

2.DroppingPoints。

3.busType。

4.OperatorName。

例如:  如果像这样输入

BoardingPoints=['abc']

DroppingPoints=['ccd','eef']

busType=['Scania Metrolink']

OperatorName=['manu']

它应该返回这两行

  

{arrivalTime:“10:30 PM”availableSeats:23 boardingPoints:[{id:   “3882”位置:“ abc ”时间:“02:30 PM”},{id:“3882”位置:   “xyz”时间:“02:30 PM”}] busType:“ Scania Metrolink ”   operatorName:“sham”commPCT:8 departureTime:“1:15 PM”   droppingPoints:[{id:“3882”位置:“dex”时间:“02:30 PM”},{id:   “3882”位置:“afg”时间:“02:30 PM”}]},

     

{到达时间:“晚上10:30”   availableSeats:23 boardingPoints:[{id:“3882”位置:“def”时间:   “02:30 PM”},{id:“3882”位置:“jkl”时间:“02:30 PM”}] busType:   “Scania”operatorName:“ manu ”commPCT:8 departureTime:“1:15 PM”   droppingPoints:[{id:“3882”位置:“ ccd ”时间:“02:30 PM”},{id:   “3882”位置:“ eef ”时间:“02:30 PM”}]}]

注意

每个输入都作为数组传递,因为我需要匹配键中的多个值。

1 个答案:

答案 0 :(得分:1)

从预期结果看,您看起来正在寻找与4个变量中的任何一个匹配的对象。以下是与之匹配的过滤器:

var bpLocations = ['abc'];
var dpLocations = ['ccdll', 'eef'];
var busTypes = ['Scania Metrolink'];
var operatorNames = ['manu'];

var result = _.filter(inputArray, function(obj) {
    return _(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0
        || _(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
        || _.includes(busTypes, obj.busType)
        || _.includes(operatorNames, obj.operatorName);
});