Home > Software engineering >  filter and map in an object array
filter and map in an object array

Time:06-27

I can't retrieve the user by his customer number. I use the includes function in filter, but this returns the error: Cannot read properties of null (reading 'includes') . Despite everything I've seen on the forum, nothing solves my problem. I have an array of user object, so I make a map on the array and then I filter here is my code:

thank you very much for help

const ClientComponent = ()=>{
   const resultSearchClient = useSelector((state)=> state.reducerSearchCriteria)
   const datasClientService = useSelector((state)=> state.reducerClientAdmin.state)
   const newArray = datasClientService.map(val=>{ return val})
   const filterArray = newArray.filter(u => {return u.number_client.includes(resultSearchClient)})
  
   return(
     <div>
       <p>{filterArray} </p>
    </div>
 )
}

export default ClientComponent;

CodePudding user response:

The error that you are receiving is thrown because number_client is null (instead of an array or string that you are expecting there). If you know that number_client is nullish, you can do:

const filterArray = newArray.filter(u => 
  return (u.number_client ?? '').includes(resultSearchClient)
})

If you expect a value everytime there, then there is a different problem with your data.

Also, what is the purpose of newArray? that map does nothing except for creating a shallow clone, right? If you neeed a shallow clone, you can just do const newArray = [...datasClientService]. But from what you sent here, newArray is not even needed. You can just create filterArray based on dataClientService since Array.filter method returns a new array.

  • Related