简体   繁体   中英

When array of objects has different keys in each object I want to filter based on the different keys

I have an object with 5 child objects. For example:

const myObject = [
 {name: 'Mike', age: '30', dob: 'January 6'},
 {name: 'Steve', age: '40'},
 {name: 'Mary', age: '30'},
 {name: 'Enrique', age: '25'},
 {name: 'Sam', age: '50'}
]

All of these objects are dynamically generated from the database. I am building a search feature that is searchable by using a text input. I can filter the table data with the below code easily with the search input if the objects have both the 'dob' key and the rest of the keys. The issue is that if new data renders inside of the table, and that new object data does not have the key 'dob' in the object, the filtering from the input returns 'Cannot read properties of undefined' for the new data. How can I make the input be able to filter/search both when objects have those keys and when an object doesn't have the key 'dob' (returns an undefined if Key isn't there in the Table data). I am working with Tanstack React Table 7.0 rc16 and their globalFiltering. I had to override the globalFilter provided by the table with this code. I have already tried checking if it's undefined and I have tried using the for in loop to detect if the key is there...etc. Any help would be appreciated.:-) The 'dob' key is always at the 0 index of the first child object if there are multiple parent objects.

const globalFilter = (rows, columns, filterValue) => {
    // filterValue is the value types into the search box
    return myArray.filter(row => {
        const rowValues = row.values;
        const theArray = Object.keys(rowValues);
        for (let i = 0; i < theArray.length ; i++) {
            console.log('rowValues', rowValues);
            const nameValue = rowValues[i].name.toLowerCase();
            const dobValue = rowValues[0].dob.toLowerCase();
            console.log('dobValue', dobValue);

            // below works if the at least one of the objects has the 'dob' key
            // returns undefined if new data comes from the database that has no 'dob' key and the search feature breaks
                
                if (nameValue.includes(String(filterValue).toLowerCase()) || 
                    dobValue.includes(String(filterValue).toLowerCase())) {

                    return row;
                }
        }
})  

You could make this dynamic by creating an array of all the object values , joining that into a single string then checking that for the filter value

return myArray.filter((row) =>
  Object.values(row).join(" ").toLowerCase().includes(filterValue.toLowerCase())
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM