[英]Filter nested data with array vales using lodash react js
考慮這個例子。 我正在使用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’
},
]
}
]
}
我想用location_id過濾上面的數據,如果只有一個id用於過濾那么
var filterplaces = _.filter(data.places,{ location: [{ location_id: this.state.selectedLocationId}] });
它返回適當的過濾數據。 知道問題是當有多個location_id時,我應該如何傳遞數組數據來過濾記錄。 讓我們說selectedLocationId將是具有locationid [2,5]的數組。
任何幫助表示贊賞。
你可以不用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);
它也可以使用some()
來完成:
filteredPlaces = data.places.filter(element => element.location.some((obj => required_ids.indexOf(obj.location_id) > -1)));
您可以使用函數作為謂詞而不是簡寫iteratee :
var filterplaces = _.filter(data.places, function(place) {
return this.state.selectedLocationIds.indexOf(place.location.location_id) >= 0;
});
希望這可以幫助
迭代集合的元素,返回所有元素的數組謂詞返回truthy。 使用三個參數調用謂詞:(value,index | key,collection)。 注意:與_.remove不同,此方法返回一個新數組。
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
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.