【问题标题】:Lodash:Getting new array with multiple key-value matches in jsonLodash:在json中获取具有多个键值匹配的新数组
【发布时间】:2016-02-24 03:59:21
【问题描述】:

我已经嵌套 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.登机点。

2.DroppingPoints.

3.busType.

4.运营商名称。

例如: 如果输入是这样的

BoardingPoints=['abc']

DroppingPoints=['ccd','eef']

busType=['Scania Metrolink'],

OperatorName=['manu']

应该返回这两行

{arrivalTime: "10:30 PM" availableSeats: 23 boardingPoints: [{id: “3882”位置:“abc”时间:“02:30PM”},{id:“3882”位置: “xyz”时间:“02:30PM”}] busType:“Scania Metrolink” 操作员姓名:“sham” commPCT:8 出发时间:“1:15 PM” dropPoints:[{id:“3882”位置:“dex”时间:“02:30PM”},{id: “3882”位置:“afg”时间:“02:30PM”}]},

{到达时间:“晚上 10:30” 可用座位:23 登机点:[{id:“3882”位置:“def”时间: “02:30PM”},{id:“3882”位置:“jkl”时间:“02:30PM”}] busType: "Scania " operatorName:"ma​​nu" commPCT: 8 出发时间: "1:15 PM" dropPoints: [{id: "3882" location: "ccd" time: "02:30PM"},{id: “3882”位置:“eef”时间:“02:30PM”}]}]

注意

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

【问题讨论】:

    标签: javascript json lodash


    【解决方案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);
    });
    

    【讨论】:

    • 谢谢 Ben 让我试试你的回答
    • busTypeoperatorName 也作为输入数组传递,例如 bploacationsdplocations
    • 然后只需使用 _.includes() 代替字符串比较“===”。改了答案。请注意,我将 busType 更改为 busTypes,将 operatorName 更改为 operatorNames,因为它们现在是数组。
    猜你喜欢
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    相关资源
    最近更新 更多