简体   繁体   English

过滤器未返回正确的结果

[英]Filter does not return the correct result

I have this array and I created this function that return me the filtered array:我有这个数组,我创建了这个 function 返回过滤后的数组:

 const result = [{ key: 'A', title: 'titleA', data: [{ name: 'miael', id: 'id4', }, { name: 'top', id: 'id2', } ] }, { key: 'B', title: 'titleB', data: [{ name: 'mich1', id: 'id12', }, { name: 'tomato', id: 'id123', } ] }, ] const doSearch = (data) => result.filter(entry => entry.data.some(item => item.name.toString().toLowerCase().includes(data.toString().toLowerCase().trim()), ), ); console.log(doSearch('mich'));

This works, but it also returns results that do not contain the searched word 'mic'这有效,但它也会返回不包含搜索词“mic”的结果

if I search for mic, I expect this result:如果我搜索麦克风,我希望得到这样的结果:

[{
  key: 'B',
  title: 'titleB',
  data: [{
      name: 'mich1',
      id: 'id12',
    },
 
  ]
}],

what am I doing wrong?我究竟做错了什么?

A couple of changes should make this work the way you wish.一些更改应该可以使这项工作按您希望的方式进行。

  • Turning doSearch into a function.doSearch变成 function。

  • Adding a searchFor parameter to the doSearch() function and passing to the.includes() call.searchFor参数添加到doSearch() function 并传递给 the.includes() 调用。

  • Using Array.reduce() to create the output array.使用Array.reduce()创建 output 数组。 Items are only added if they include the searchFor value.只有包含 searchFor 值的项目才会被添加。

 const input = [{ key: 'A', title: 'titleA', data: [{ name: 'miael', id: 'id4', }, { name: 'top', id: 'id2', } ] }, { key: 'B', title: 'titleB', data: [{ name: 'mich1', id: 'id12', }, { name: 'tomato', id: 'id123', } ] }, ] const doSearch = (searchFor, arr) => arr.reduce((acc, { key, title, data }) => { const filteredData = data.filter(({ name }) => { return name.toLowerCase().includes(searchFor.toLowerCase()) }); if (filteredData.length > 0) { acc.push({ key, title, data: filteredData }); } return acc; }, []); console.log(doSearch('mic', input ));

You can keep your current logic and add a map with the same filter for entry.data :您可以保留当前的逻辑并添加一个mapentry.data相同的过滤器:

 const result = [{ key: 'A', title: 'titleA', data: [{ name: 'miael', id: 'id4', }, { name: 'top', id: 'id2', } ] }, { key: 'B', title: 'titleB', data: [{ name: 'mich1', id: 'id12', }, { name: 'tomato', id: 'id123', } ] }, ] function nameFilter(item, data) { return item.name.toString().toLowerCase().includes(data.toString().toLowerCase().trim()) } const doSearch = (data) => result.filter(entry => entry.data.some(item => nameFilter(item, data) ), ).map(entry => ({...entry, data: entry.data.filter(item => nameFilter(item, data)) })); console.log(doSearch('mich'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM