as seen in my title I am facing a problem that needs a solution. I am trying to filter my object, but not only based on keys. But also based on the value of the allowed keys.
This is what I got so far:
const handleSearch = (searchValue) => {
if(searchValue !== '') {
const allowed = ['name', 'title'];
let list = props.search.list;
const filtered = Object.keys(list)
.filter((key) => allowed.includes(key))
.reduce((obj, key) => {
obj[key] = list[key];
return obj;
}, {});
const filteredArray = Object.entries(filtered)
props.search.onChange(filteredArray)
} else {
props.search.onChange(props.search.list)
}
}
Structure of the list object:
0: {name: "John', title: 'Owner'}
1: {name: "Jane", title: 'Admin'}
Wanted results:
Filtered array that shows the keys filtered aswell as the search value.
And I don't know where I should integrate the filtering by the values aswell. This has been giving me a headache for the past few hours. And hope someone here is experienced with these kinds of issues/logic.
Thanks for reading.
Kind regards.
CodePudding user response:
const handleSearch = (searchValue) => {
if (searchValue !== '') {
const allowed = ['name', 'title'];
const list = props.search.list;
const filtered = list
.filter(obj =>
Object.keys(obj)
.some(k => allowed.includes(k))
)
.filter(obj =>
Object.values(obj)
.map(v => v.toLocaleLowerCase())
.some(v => v.includes(searchValue.toLowerCase()))
)
props.search.onChange(filtered)
} else {
props.search.onChange(props.search.list)
}
}
Example
Let's assume props
as:
const props = {
search: {
list: [
{ name: "John", title: 'Owner' },
{ name: "Jane", title: 'Admin' },
{ name: "Reza", title: 'Owner' }
],
onChange: x => console.log(x)
},
}
handleSearch("own")
// [ { name: 'John', title: 'Owner' }, { name: 'Reza', title: 'Owner' } ]
handleSearch("jane")
// [ { name: 'Jane', title: 'Admin' } ]
handleSearch("something")
// []