gpt4 book ai didi

javascript - 根据传入的输入过滤对象数组 : Javascript

转载 作者:行者123 更新时间:2023-12-01 16:04:03 25 4
gpt4 key购买 nike

我有一组具有以下结构的对象

arr = [ { name: "abc" , items: ["itemA","itemB","itemC"], days :138} ,
{ name: "def" , items: ["itemA1","itemB2","itemC1"], days :157} ,
{ name: "hfg" , items: ["itemAN","itemB7","itemC7"], days :189} ]

该数组需要根据传递的搜索输入进行过滤。我能够为 name 实现相同的效果,天没有被过滤。
也有人可以帮助如何搜索 items数组,因此它根据传递的输入过滤行
这是我尝试过的
  handleSearch = (arr, searchInput) => {
let filteredData= arr.filter(value => {
return (
value.name.toLowerCase().includes(searchInput.toLowerCase()) ||
value.days.toString().includes(searchInput.toString())
);
});
console.log(filteredData);
//this.setState({ list: filteredData });
}


最佳答案

您可以使用 Array#some 然后执行您已经完成的相同类型的匹配:

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

  handleSearch = (arr, searchInput) => {
const filteredData = arr.filter(value => {
const searchStr = searchInput.toLowerCase();
const nameMatches = value.name.toLowerCase().includes(searchStr);
const daysMatches = value.days.toString().includes(searchStr);
const oneItemMatches = value.items.some(item => item.toLowerCase().includes(searchStr));

return nameMatches || daysMatches || oneItemMatches;
});
console.log(filteredData);
//this.setState({ list: filteredData });
}

关于javascript - 根据传入的输入过滤对象数组 : Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62916784/

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