I am faced with a problem and I don't understand how I can solve it.
I have a service where I return the following JSON:
{
"data": [
{
"data": 179,
"data_form": "Finished - Form Covid-19 Test 1",
"form": 144,
"user": 1,
"status": "Finished"
},
{
"data": 176,
"data_form": "In process - Form Covid-19 Test 2",
"form": 144,
"user": 1,
"status": "Finished"
},
{
"data": 177,
"data_form": "Finished - Form Covid-19 Test 3",
"form": 144,
"user": 1,
"status": "In process"
},
{
"data": 178,
"data_form": "Finished - Form Covid-19 Test 4",
"form": 144,
"user": 1,
"status": "In process"
}
]
}
I am using a PIPE where I am sending it my array, the value I want to filter and the column where that value is:
<ion-list
*ngFor="let form of forms | filter: searchValue: ['status','data_form','data']">
<app-form-user [form]="form">
</app-form-user>
</ion-list>
It works if I indicate the column:
return array.filter(
//It works
item=> item[column[0]].toLowerCase().includes( text )
);
The idea is to look for the value in all the columns that you indicate to the pipe, I tried the following:
1.
return array.filter(
item=> item[column.forEach((data) => found = data )].toLowerCase().includes( text );
);
return array.filter(
item=>Object.keys(column).every(key =>
item[key] == column[key]
)
);
return array.filter(
item=> column.forEach((data) => item[data].toLowerCase().includes( text ))
);
I hope you can help me, thank you.
CodePudding user response:
Works without needing the pass the column, searches all the available columns.
One line code
This filter goes thru each key that you have to check values and return the result.
Detailed explanation:
1) Base is the object you posted and assuming you want to filter the "data"
2) First filter goes thru all the elements in the array
3) second filter goes thru all the keys in the object which is element in the array
4) Checking if the column has the data
5) returns the array of elements if matched
const text = 'Test 2';
return array.filter(v=> Object.keys(v).filter(key=> v[key].toString().toLowerCase().includes(text.toString().toLowerCase())).length > 0)
And result is:
CodePudding user response:
I will use .map() to go through each key of each item, and decide does it found the specific values or not, and return it on filter level
return array.filter(item => {
let found = false;
Object.keys(item).map(x => {
found = found || item[x].toLowerCase().includes( text );
});
return found;
});