I\'m wondering what is the cleanest way, better way to filter an array of objects depending on a string keyword
. The search has to be made in any properties of
Use Object.keys to loop through the properties of the object. Use reduce and filter to make the code more efficient:
const results = arrayOfObject.filter((obj)=>{
return Object.keys(obj).reduce((acc, curr)=>{
return acc || obj[curr].toLowerCase().includes(term);
}, false);
});
Where term is your search term.
You could filter it and search just for one occurence of the search string.
Methods used:
Array#filter, just for filtering an array with conditions,
Object.keys for getting all property names of the object,
Array#some for iterating the keys and exit loop if found,
String#toLowerCase for getting comparable values,
String#includes for checking two string, if one contains the other.
function filterByValue(array, string) {
return array.filter(o =>
Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}
const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }];
console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]
console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]
.as-console-wrapper { max-height: 100% !important; top: 0; }
This code checks all the nested values until it finds what it's looking for, then stops and returns true to the "array.filter" for the object it was searching inside(unless it can't find anything - returns false). When true is returned, the object is added to the array that the "array.filter" method returns.
const data = [{
a: "a",
b: {
c: "c",
d: {
e: "e",
f: [
"g",
{
i: "i",
j: {},
k: []
}
]
}
}
},
{
a: "a",
b: {
c: "c",
d: {
e: "e",
f: [
"g",
{
i: "findme",
j: {},
k: []
}
]
}
}
},
{
a: "a",
b: {
c: "c",
d: {
e: "e",
f: [
"g",
{
i: "i",
j: {},
k: []
}
]
}
}
}
];
function getState(data: any, inputValue: string, state = false) {
for (const value of Object.values(data)) {
if (typeof value === 'object' && value !== null && Object.keys(value).length > 0 && state === false) {
state = getState(value, inputValue, state);
} else {
if (state === false) {
state = JSON.stringify(value).toLowerCase().includes(inputValue.toLowerCase());
} else {
return state;
}
}
}
return state;
}
function filter(data: [], inputValue) {
return data.filter((element) => getState(element, inputValue));
}
console.log(filter(data, 'findme'));
If you need to search for objects that contain multiple keywords, to narrow down the filtered objects further, which makes the filter even more user friendly.
const data = [{
a: "a",
b: {
c: "c",
d: {
e: "findme2",
f: [
"g",
{
i: "i",
j: {},
k: []
}
]
}
}
},
{
a: "a",
b: {
c: "c",
d: {
e: "e",
f: [
"g",
{
i: "findme",
j: {},
k: []
}
]
}
}
},
{
a: "a",
b: {
c: "c",
d: {
e: "findme2",
f: [
"g",
{
i: "findme",
j: {},
k: []
}
]
}
}
}
];
function filter(data: [], inputValue: string) {
return data.filter((element) => checkState(element, inputValue));
}
function checkState(element: any, inputValue: string) {
const filterValues = inputValue.trim().split(' ');
const states: boolean[] = [];
for (let index = 0; index < filterValues.length; index++) {
states[index] = getState(element, filterValues[index]);
}
return states.every(state => state === true);
}
function getState(data: any, inputValue: string, state = false) {
for (const value of Object.values(data)) {
if (typeof value === 'object' && value !== null && Object.keys(value).length > 0 && state === false) {
state = getState(value, inputValue, state);
} else {
if (state === false) {
state = JSON.stringify(value).toLowerCase().includes(inputValue.toLowerCase());
} else {
return state;
}
}
}
return state;
}
console.log(filter(data, 'findme')); // gets all objects that contain "findme"
console.log(filter(data, 'findme findme2')); // gets all objects that contain "findme" and "findme2"
You can always use array.filter()
and then loop through each object and if any of the values match the value you are looking for, return that object.
const arrayOfObject = [{
name: 'Paul',
country: 'Canada',
}, {
name: 'Lea',
country: 'Italy',
}, {
name: 'John',
country: 'Italy',
}, ];
let lea = arrayOfObject.filter(function(obj){
//loop through each object
for(key in obj){
//check if object value contains value you are looking for
if(obj[key].includes('Lea')){
//add this object to the filtered array
return obj;
}
}
});
console.log(lea);
Well when we already know that its not going to be a search on an object with methods, we can do the following for saving bit on time complexity :
function filterByValue(array, value) {
return array.filter((data) => JSON.stringify(data).toLowerCase().indexOf(value.toLowerCase()) !== -1);
}
One way would be to use Array#filter
, String#toLowerCase
and String#indexOf
like below.
const arrayOfObject = [{
name: 'Paul',
country: 'Canada',
}, {
name: 'Lea',
country: 'Italy',
}, {
name: 'John',
country: 'Italy',
}];
function filterByValue(arrayOfObject, term) {
var ans = arrayOfObject.filter(function(v,i) {
if(v.name.toLowerCase().indexOf(term) >=0 || v.country.toLowerCase().indexOf(term) >=0) {
return true;
} else false;
});
console.log( ans);
}
filterByValue(arrayOfObject, 'ita');