[英]filter every single value using onChangeText from nested array in react-native
我有一個帶有嵌套子元素的數組,子元素可以是一個或最多n個值, 我正在嘗試在組件內部實現局部過濾器 。 當用戶在textInput中鍵入任何內容時 , 應用程序將開始根據他/她鍵入的單詞向用戶顯示建議,而該建議將來自我的預定義數組。
這是我現在正在使用的代碼:-
export function onSearch(categoryList, searchText) {
var searchList = [];
return function(dispatch) {
categoryList.map((item, i) => {
if (item.title.includes(searchText)) {
searchList.push(item);
}
});
dispatch({
type: types.Search_Success,
payload: searchList
});
};
}
AS在上述方法中,您可以看到代碼只會將值過濾為父值,因此我嘗試通過添加條件來添加代碼 :-
if(item.children.length>0){
item.children.map((item, i) => {
if (item.title.includes(searchText)) {
searchList.push(item);
}
});
}
但問題是我可以生很多孩子,所以我不能在代碼中放入這樣的條件
這是我的數組的樣子:-
[{
"id": "38",
"title": "What's New",
"url": "what-is-new"
}, {
"id": "20",
"title": "Women",
"url": "women",
"children": [{
"id": "21",
"title": "Tops",
"url": "tops-women",
"children": [{
"id": "23",
"title": "Jackets",
"url": "jackets-women"
}, {
"id": "24",
"title": "Hoodies & Sweatshirts",
"url": "hoodies-and-sweatshirts-women"
}, {
"id": "25",
"title": "Tees",
"url": "tees-women"
}, {
"id": "26",
"title": "Bras & Tanks",
"url": "tanks-women"
}]
}, {
"id": "22",
"title": "Bottoms",
"url": "bottoms-women",
"children": [{
"id": "27",
"title": "Pants",
"url": "pants-women"
}, {
"id": "28",
"title": "Shorts",
"url": "shorts-women"
}]
}]
}, {
"id": "11",
"title": "Men",
"url": "men",
"children": [{
"id": "12",
"title": "Tops",
"url": "tops-men",
"children": [{
"id": "14",
"title": "Jackets",
"url": "jackets-men"
}, {
"id": "15",
"title": "Hoodies & Sweatshirts",
"url": "hoodies-and-sweatshirts-men"
}, {
"id": "16",
"title": "Tees",
"url": "tees-men"
}, {
"id": "17",
"title": "Tanks",
"url": "tanks-men"
}]
}, {
"id": "13",
"title": "Bottoms",
"url": "bottoms-men",
"children": [{
"id": "18",
"title": "Pants",
"url": "pants-men"
}, {
"id": "19",
"title": "Shorts",
"url": "shorts-men"
}]
}]
}]
當我鍵入“ m”時,我不需要的是它應該給我所有包含“ m”的標題。
如果我對我的問題不太清楚,請告訴我。
問候
我建議編寫一個遞歸函數來解決您的問題,如下所示:
export const onSearch = (categoryList, searchText) => {
return dispatch => {
const suggestions = []
const addToSuggestions = item => {
if (item.title.includes(searchText)) {
suggestions.push(item)
}
if (item.children) {
item.children.forEach(addToSuggestions)
}
}
categoryList.forEach(addToSuggestions)
dispatch({
type: types.Search_Success,
payload: suggestions
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.