Home > other >  Filter from key value objects in reactjs
Filter from key value objects in reactjs

Time:10-18

I am creating searchbar to filter key value data objects. I am getting filter is not a function error while doing search. Is there any other function to filter in key value pair objects ?

Data :-

{
  meta_city : {
    label: "City"
    values: (5) ["DL", "KA", "GJ", "MH", "UP"]
   },
  meta_country : {
    label: "Country"
    values: (5) ["IN", "US", "CA"]
   }
}

Handle search (filterData data is local state) :-

const handleSearchFilter = (event) => {
    const searchWord = event.target.value;
    const newFilter = Object.keys(filterData).map((key) => {
      filterData[key].filter((value) => {
        return value.includes(searchWord);
      });
    });
    setFilterData(newFilter);
  };
<div className="mp-input-field-container">
     <input
       className="mp-input"
       placeholder="Search"
       onChange={handleSearchFilter}                    
     />
</div>

CodePudding user response:

You should use reduce like this:

const handleSearchFilter = (event) => {
  const searchWord = event.target.value;
  const newFilter = Object.keys(filterData).reduce((result, key) => {
    if (filterData[key].values.includes(searchWord)) {
      result.push(filterData[key]);
    };
    return result;
  }, []);
  setFilterData(newFilter);
};

In this example I'm returning an array result. you can return an object if you want.

CodePudding user response:

Filter does not exist on a string type. When filterData[key] is called, key has a value of label. filterData["label"] returns a string "City".

try

const searchWord = (word) => Object.values(filterData).filter((data) => data.values?.includes(word));

const handleSearchFilter = (event) => {
  const word = event.target.value;
  const [newFilter] = searchWord(word)
  setFilterData(newFilter);
}

searchWord returns if you search "DL"

[
  {
    label: 'City',
    values: [ 'DL', 'KA', 'GJ', 'MH', 'UP' ]
  }
]

Was that the result you were looking for?

Here is the code snippet to prove the solution works:

var filterData = {
  meta_city : {
    label: "City",
    values: ["DL", "KA", "GJ", "MH", "UP"]
   },
  meta_country : {
    label: "Country",
    values: ["IN", "US", "CA"]
   }
}


const searchWord = (word) => Object.values(filterData).filter((data) => data.values.includes(word));


console.log(searchWord("DL"))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related