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) {
return true;
}
}
return false;
});
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')));
});
Post a Comment for "Lodash:Getting New Array With Mulitple Matches In JSON"