React Filter Ignore null Variables

60 Views Asked by At

have an array of objects I'm showing in a table in react and adding a filter to the top of each table column. Most columns are NOT NULL but there are a few that can be null. These columns are failing when trying to filter them. Trying to find a way to bypass null variables. Showing what I have, first set works when no null values, second is the one I am attempting to fix.

{data
    .filter((row) => 
        !searchedValueQuote || row.QuoteNo
        .toString()
        .toLowerCase()                                              
        .includes(searchedValueQuote.toString().toLowerCase())
    )
    .filter((row) => 
        !searchedValueStatus || row.dataValues.jobStatus || typeof row.dataValues.jobStatus !== null
        .toString()
        .toLowerCase()                                           
        .includes(searchedValueStatus.toString().toLowerCase())
    )
    .map( 
        ....
    )
}

The error is

TypeError: Cannot read properties of null (reading 'toString')
2

There are 2 best solutions below

5
Jason Ming On BEST ANSWER

Please try this.

{data
    .filter((row) => {
        if (!searchedValueQuote) { return true; }
        if (!row || !row.QuoteNo) { return false; }
        
        return row.QuoteNo
            .toString()
            .toLowerCase()                                              
            .includes(searchedValueQuote.toString().toLowerCase())
    })
    .filter((row) => {
        if (!searchedValueStatus) { return true; }
        if (!row || !row.dataValues || !row.dataValues.jobStatus) { return false; }
        
        return row.dataValues.jobStatus
            .toString()
            .toLowerCase()                                           
            .includes(searchedValueStatus.toString().toLowerCase())
    })
    .map( 
        ....
    )
}
2
Harishbabu On

Like this you can try :

{data
        .filter((row) => 
            !searchedValueQuote || (row.QuoteNo && row.QuoteNo.toString().toLowerCase().includes(searchedValueQuote.toString().toLowerCase()))
        )
        .filter((row) => 
            !searchedValueStatus || (row.dataValues.jobStatus !== null && row.dataValues.jobStatus.toString().toLowerCase().includes(searchedValueStatus.toString().toLowerCase()))
        )
        .map(
            // Your mapping logic here
        )
    

}