Skip to content Skip to sidebar Skip to footer

Lodash:getting New Array With Mulitple Matches In Json

I have a nested JSON look like this [ {arrivalTime: '10:30 PM' availableSeats: 23 boardingPoints: [{id: '3882' location: 'abc' time: '02:30PM'},{id: '3882' location: 'xyz' time: '

Solution 1:

You can use a series of lodash calls with some logic to get the expected results. Something like this:

var _ = require('lodash');

var result = [
    {
        arrivalTime: "10:30 PM",
        availableSeats: 23,
        boardingPoints: [{
            id: "3882",
            location: "abc",
            time: "02:30PM"
        },{
            id: "3882",
            location: "xyz",
            time: "02:30PM"
        }],
        busType: "Scania Metrolink",
        commPCT: 8,
        departureTime: "1:15 PM",
        droppingPoints: null,
    },
    {
        arrivalTime: "10:30 PM",
        availableSeats: 23,
        boardingPoints: [{
            id: "3882",
            location: "def",
            time: "02:30PM"
        },{
            id: "3882",
            location: "jkl",
            time: "02:30PM"
        }],
        busType: "Scania ",
        commPCT: 8,
        departureTime: "1:15 PM",
        droppingPoints: null
    }
];
var locations = ['xyz'];

var f = _.filter(result, function(obj) {
    var value = _.map(obj.boardingPoints, 'location');       
    var i, len;

    for (i = 0, len = locations.length; i < len; i++) {
        if (_.indexOf(value, locations[i]) >= 0) {
            returntrue;
        }
    }
    returnfalse;
});

console.log(f);  // result is your eg-a

when

locations = ['xyz', 'def'];

the result will be your eg-b

Another approach to the solution is to chain the calls with intersection():

var f = _.filter(result, function(obj) {
  return _.chain(obj.boardingPoints).map('location').intersection(locations).value().length > 0;
});

Solution 2:

var result = _.filter(yourArray, function(item) {
    return _.size(_.intersection(['xyz', 'def'], _.map(item.boardingPoints, 'location')));
});

https://jsfiddle.net/qeaabov9/2/

Post a Comment for "Lodash:getting New Array With Mulitple Matches In Json"