How can I efficiently search through an array of objects by specifying the fields to search within a function call and filtering out specific values? For example:
const src = [ { id:1, name: "name1", age: 25}, { id: 2, name: "name2", age: 33} ]
If I only want to search for values in the name
and age
fields while excluding the id field, how can this be achieved in code?
function contains(text, subStr) {
return text.includes(subStr);
}
const searchInData = (searchString, searchData, fieldsForSearch) => {
const keyword = searchString.toLocaleLowerCase();
let filteredData = searchData;
if (keyword) {
filteredData = searchData?.filter((item) => {
const { ...fields } = item;
return Object.keys(fields).some(key => fieldsForSearch.includes(key) && contains(fields[key], keyword));
});
}
return filteredData;
};
Is it possible to pass in an array of field names to limit the search to only those specified fields? Like so,
searchInData(searchString, searchData, ['name', 'age'])