Home > OS >  Filtering through nested JSON values in Javascript (React)
Filtering through nested JSON values in Javascript (React)

Time:12-14

I am having a nested json file fetched through api which is kind of a nested object. An example of the json file is as follows:

{
   "trees":{
      "name":"a",
      "age":"9",
      "height":"10",
      "location":"park"
   },
   "cars":{
      "name":"b",
      "age":"30",
      "height":"10",
      "location":"park"
   },
   "bikes":{
      "name":"c",
      "age":"110",
      "height":"10",
      "location":"park"
   },.........................

I am building a search functionality wherein whatever the user searches for can be filtered in name and location of the above json file and send to child component (eg. searchTerm =c then send name age height location where there is c in name or location)

This is how I mapped through the same json is completely different component which was working fine.

{ Object.entries(props.data).map(
    ([key, {
      ...e
     }]) => {
        return (<tr>
            <SingleData key={key}
                {...e}
            /> </tr>
        )
    }
)}



const searchHandler = (string) => {
     setsearchTerm(string)
     if (searchTerm!==""){
       const filtered= Object.entries(Data).filter(
         ([key, { 
           ...e
          }]) => {
             return ( 
               console.log(Object.values(name).toLowerCase().includes(searchTerm.toLowerCase()))
             )
         }
     )
       setSearchResults(filtered)
     }
     else{
       setSearchResults(Data)
     }
   }

Here I tried to send data as setSearchResults to child component after filtering. searchTerm is in useState which is getting updated with the search string of user.

But this method is giving me nothing. Please hele me try to figure out how to make this work

CodePudding user response:

If you want to have filtered item as nested array include [key, obj] you can do it like this:

const data = {
  "trees": {
    "name": "a",
    "age": "9",
    "height": "10",
    "location": "park"
  },
  "cars": {
    "name": "b",
    "age": "30",
    "height": "10",
    "location": "park"
  },
  "bikes": {
    "name": "c",
    "age": "110",
    "height": "10",
    "location": "park"
  }
}

const searchTerm = 'C';
const filtered = Object.entries(data).filter(
    ([key, obj]) =>obj.name.toLowerCase().includes( searchTerm.toLowerCase() ) );

console.log(filtered)

if you want to have just filtered objects in the filtered variable, you can map over your result after you finished your search like this:

const filtered = Object.entries(data).filter(
([key, obj]) =>obj.name.toLowerCase().includes( searchTerm.toLowerCase() ) ).map(item => item[1]);
  • Related