Home > Software engineering >  React filter multiple object key
React filter multiple object key

Time:08-15

trying to work with Minimals.cc and I have a problem with the search feature that include only the names and that I need to extends to other key of the objects I'm filtering (filterAll). Here is the code:

function applySortFilter({ tableData, comparator, filterName, filterCircle, filterAll }) {
  const stabilizedThis = tableData.map((el, index) => [el, index]);

  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0]);
    if (order !== 0) return order;
    return a[1] - b[1];
  });

  tableData = stabilizedThis.map((el) => el[0]);


 // this is the one i'm trying to make that should includes both item.name and item.circle_name

  if (filterAll) {
    tableData = tableData.filter((item) => item.name.toLowerCase().indexOf(filterAll.toLowerCase()) !== -1);
  }


  if (filterName) {
    tableData = tableData.filter((item) => item.name.toLowerCase().indexOf(filterName.toLowerCase()) !== -1);
  }

  if (filterCircle) {
    tableData = tableData.filter((item) => item.circle_name.toLowerCase().indexOf(filterCircle.toLowerCase()) !== -1);
  }


  return tableData;
}

I tried playing with && and || in the filter method to add item.circle_name and item.name but it did not work (at least for the way I did it). Thanks in advance.

CodePudding user response:

you need to return the tableData after filterAll to not execute other if conditions, also you need to check if filterAll includes name or circle_name not the reverse.

if (filterAll) {
    tableData = tableData.filter((item) => filterAll.toLowerCase().includes(item.name.toLowerCase()) || filterAll.toLowerCase().includes(item.circle_name.toLowerCase());
  }

CodePudding user response:

After trying more the answer that would work is:

if (filterAll) {
    tableData = tableData.filter((item) => (item.name.toLowerCase().indexOf(filterAll.toLowerCase()) && item.circle_name.toLowerCase().indexOf(filterAll.toLowerCase())) !== -1);
  }
  • Related