I have the following array:
arr = [
{ id: '1', name: 'Something', code: 'A33', number: '67', house: 'St55' },
{ id: '2', name: 'Another', code: '55', number: '004', house: 'ES' },
{ id: '3', name: 'One more', code: 'DAE', number: '003', house: 'R5' },
];
I'm using the function bellow (source) for a search bar to search all fields of array of objects (arr) depends on the user inputs (value):
function findInValues(arr, value) {
value = String(value).toLowerCase();
return arr.filter(o =>
Object.entries(o).some(entry =>
String(entry[1]).toLowerCase().includes(value)
)
);
}
But to resolve my case, the function would can search only on the keys name and house, the search must ignore id,code and number.
For example:
value = 55
Result = [
{ id: '1', name: 'Something', code: 'A33', number: '67', house: 'St55' }
];
What should I do in my case?
CodePudding user response:
You can destructure the keys id, code and number that you want to ignore from the object you're filtering and then grab the remaining object without these properties using the rest syntax ...o. You can then use the same code that you're currently using to search the o object. Note that below, I have also changed Object.entries() to be just Object.values() as your code isn't using the key from the entry array:
const arr = [
{ id: '1', name: 'Something', code: 'A33', number: '67', house: 'St55' },
{ id: '2', name: 'Another', code: '55', number: '004', house: 'ES' },
{ id: '3', name: 'One more', code: 'DAE', number: '003', house: 'R5' },
];
function findInValues(arr, value) {
value = String(value).toLowerCase();
return arr.filter(({id, code, number, ...o}) =>
Object.values(o).some(val =>
String(val).toLowerCase().includes(value)
)
);
}
console.log(findInValues(arr, 55));
Otherwise, if you know the keys you want to search (ie: name and house), then you can check those explicitly:
const arr = [
{ id: '1', name: 'Something', code: 'A33', number: '67', house: 'St55' },
{ id: '2', name: 'Another', code: '55', number: '004', house: 'ES' },
{ id: '3', name: 'One more', code: 'DAE', number: '003', house: 'R5' },
];
function findInValues(arr, value) {
value = String(value).toLowerCase();
const search = ['name', 'house'];
return arr.filter(o => search.some(key => o[key].toLowerCase().includes(value)));
}
console.log(findInValues(arr, 55));
CodePudding user response:
Shorter version! :)
function findInValues(arr, value) {
value = String(value).toLowerCase();
return arr.filter(({
name,
house
}) =>
(name.toLowerCase() == value || house.toLowerCase() == value)
);
}
