Files
encoach_frontend/src/utils/search.ts

43 lines
1.3 KiB
TypeScript

/*fields example = [
['id'],
['companyInformation', 'companyInformation', 'name']
]*/
const getFieldValue = (fields: string[], data: any): string | string[] => {
if (fields.length === 0) return data;
const [key, ...otherFields] = fields;
if (Array.isArray(data[key])) {
// If the key points to an array, like "participants", iterate through each item in the array
return data[key]
.map((item: any) => getFieldValue(otherFields, item)) // Get the value for each item
.filter(Boolean); // Filter out undefined or null values
} else if (data[key] !== undefined) {
// If it's not an array, just go deeper in the object
return getFieldValue(otherFields, data[key]);
}
return data;
};
export const search = (text: string, fields: string[][], rows: any[]) => {
const searchText = text.toLowerCase();
return rows.filter((row) => {
return fields.some((fieldsKeys) => {
const value = getFieldValue(fieldsKeys, row);
if (Array.isArray(value)) {
// If it's an array (e.g., participants' names), check each value in the array
return value.some((v) => v && typeof v === "string" && v.toLowerCase().includes(searchText));
}
if (typeof value === "string") {
return value.toLowerCase().includes(searchText);
}
if (typeof value === "number") {
return (value as Number).toString().includes(searchText);
}
});
});
};