Lodash:Getting new array with multiple key-value matches in json

本小妞迷上赌 提交于 2019-12-12 03:18:48

问题


I have nessted JSON look like this

[
    {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"}]
    }
    ]

From this i want to get new array that matches the these key values. Here is the keys.

1.BoardingPoints.

2.DroppingPoints.

3.busType.

4.OperatorName.

Eg: if the input like this

BoardingPoints=['abc']

DroppingPoints=['ccd','eef']

busType=['Scania Metrolink'],

OperatorName=['manu']

It should returns these two rows

{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"}] } ]

Note

Each input is passed as an array because i need to match multiple values in the keys.


回答1:


From the expected result, it looks like you are looking for the objects that match any of the 4 variables. Here is the filter that will match them:

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);
});


来源:https://stackoverflow.com/questions/35592988/lodashgetting-new-array-with-multiple-key-value-matches-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!