gpt4 book ai didi

javascript - 使用 onChangeText 从 React-native 中的嵌套数组中过滤每个值

转载 作者:行者123 更新时间:2023-12-03 02:17:40 25 4
gpt4 key购买 nike

我有一个包含嵌套子项的数组,子项可以是一个或最多 n 个值,我正在尝试在我的组件内实现本地过滤器当用户在 textInput 中输入任何内容时应用程序将开始根据用户输入的单词向用户显示建议,并且建议将来 self 预定义的数组。 p>

这是我现在正在使用的代码:-

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
});
};
}

在上述方法中,您可以看到代码将仅过滤到父值的值,因此我尝试通过添加条件来添加代码,例如:-

if(item.children.length>0){
item.children.map((item, i) => {
if (item.title.includes(searchText)) {
searchList.push(item);
}
});
}

但是问题是我可以有很多 child ,所以我不能在代码中添加这样的条件

这是我的数组的样子:-

[{
"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
})
}
}

关于javascript - 使用 onChangeText 从 React-native 中的嵌套数组中过滤每个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49298923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com