Reputation: 743
Consider this example. I am using Lodash
"data": {
“places”: [
{
place: 1,
place name: ‘123’
location: [
{
location_id: 1,
location_name: ‘xyz’
},
{
location_id: 2,
location_name: ‘abc’
},
{
location_id: 3,
location_name: ‘etc’
},
]
},
{
place: 2,
place name: ‘456’
location: [
{
location_id: 1,
location_name: ‘xyz’
},
{
location_id: 3,
location_name: ‘abc’
},
{
location_id: 4,
location_name: ‘etc’
},
]
} ,
{
place: 3,
place name: ‘123’
location: [
{
location_id: 5,
location_name: ‘xyz’
},
{
location_id: 6,
location_name: ‘abc’
},
{
location_id: 2,
location_name: ‘etc’
},
]
}
]
}
I want to filter the above data with location_id if theres only one id to filter with then
var filterplaces = _.filter(data.places,{ location: [{ location_id: this.state.selectedLocationId}] });
it return proper filter data. Know the issue is when there is more than one location_id then how should i pass array data to filter records. lets say selectedLocationId will be array which has locationid [2,5].
Any help is appreciated Thanks in advance.
Upvotes: 1
Views: 1021
Reputation: 5940
You could do it without lodash:
data.places.forEach(element =>
element.location.filter(obj => required_ids.indexOf(obj.location_id) > -1).length
&& filterplaces.push(element)
);
var data = {
"places": [{
place: 1,
place_name: "123",
location: [{
location_id: 1,
location_name: "xyz"
},
{
location_id: 2,
location_name: "abc"
},
{
location_id: 3,
location_name: "etc"
},
]
},
{
place: 2,
place_name: "456",
location: [{
location_id: 1,
location_name: "xyz"
},
{
location_id: 3,
location_name: "abc"
},
{
location_id: 4,
location_name: "etc"
},
]
},
{
place: 3,
place_name: "123",
location: [{
location_id: 5,
location_name: "xyz"
},
{
location_id: 6,
location_name: "abc"
},
{
location_id: 2,
location_name: "etc"
},
]
}
]
};
let required_ids = [1, 2];
var filterplaces = [];
data.places.forEach(element => element.location.filter(obj => required_ids.indexOf(obj.location_id) > -1).length && filterplaces.push(element));
console.log(filterplaces);
It could also be done using some()
:
filteredPlaces = data.places.filter(element => element.location.some((obj => required_ids.indexOf(obj.location_id) > -1)));
Upvotes: 2
Reputation: 455
Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection). Note: Unlike _.remove, this method returns a new array.
var filter = _.filter(data.places, function(p) {
if (p.length === 1) {
// write logic to return true or not if locaion is onnly 1
} else {
// write logic for more than 1 location id
}
});
https://lodash.com/docs/#filter for more detaiols
Upvotes: 0
Reputation: 678
you can use a function as your predicate instead of shorthand iteratee:
var filterplaces = _.filter(data.places, function(place) {
return this.state.selectedLocationIds.indexOf(place.location.location_id) >= 0;
});
Hope this helps
Upvotes: 1