I'm trying to implement a custom filter after using Angular's inbuilt Key Value pipe
I have an array with values for example
object= [
{ key: "Added_By", value: "Yi" },
{ key: "Assigned_To", value: "-" },
{ key: "Bought_Date", value: 43810 },
{ key: "Brand", value: "Samsung PM863" },
{ key: "Capacity", value: 3.84 },
]
I want to filter based on multiple incoming values but incoming values vary for example
It Could be 1 key/Value
Filter= [{ key: "Added_By", value: "Yi" }]// Return Object
or multiple
Filter= [{ key: "Added_By", value: "Yi" }, { key: "Bought_Date", value: 43810 }] //both matches return object
Filter= [{ key: "Added_By", value: "ABC" }, { key: "Bought_Date", value: 43810 }] //1 match but 1 doesn't return false
I want to return object if all the conditions are met
For a single key/value I tried
let Key= Filter[0].key
let Value=Filter[0].value
let KeyFilter = object.filter(x => x.key === Key)
if (KeyFilter[0].value.toString().toLowerCase().indexOf(Value.toLowerCase()) !== -1)
return items
But this approach only works only when 1 object is present in filter array
I've created a function that accepts an array of objects , and an object with key: value pairs .
The keys of objects in the array must match with object keys to work.
I always use it when I need to filter an array based on various conditions.
export const filterArray = (filterData, toBeFiltered) => {
return toBeFiltered.filter(item => {
for (const key in filterData) {
if (item[key] === null || item[key] === undefined) {
return false;
} else {
if (typeof filterData[key] === 'string') {
if (!(item[key]).toLowerCase().includes((filterData[key].trim()).toLowerCase())) {
return false;
}
} else if (item[key] !== filterData[key]) {
return false;
}
}
}
return true;
});
};
Hope it helps.
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.