Reputation: 528
I am working on JavaScript filter.I have to filter data with one column or more than one column with following requirement and please see below example of object.
var arr = [
{
"t_id" : "abc",
"s_id" : "pai"
},
{
"t_id" : "pai",
"s_id" : "par"
},
{
"t_id" : "pai",
"s_id" : "pas"
},
{
"t_id" : "pai",
"s_id" : "pai"
},
{
"t_id" : "par",
"s_id" : "pas"
}
]
When I will apply filter for with field t_id with 'pai' value so it will return below object.
{
"t_id" : "pai",
"s_id" : "par"
},
{
"t_id" : "pai",
"s_id" : "pas"
},
{
"t_id" : "pai",
"s_id" : "pai"
}
And when I will apply filter using field s_id with 'pai' value it should return below object.
{
"t_id" : "abc",
"s_id" : "pai"
},
{
"t_id" : "pai",
"s_id" : "par"
},
{
"t_id" : "pai",
"s_id" : "pas"
},
{
"t_id" : "pai",
"s_id" : "pai"
}
Basically when I will apply filter for field 's_id'. It will consider filter for 't_id' too. thanks in advance.
Upvotes: 0
Views: 239
Reputation: 386766
You could take an array for the keys to check and check if the property is equal to the wanted value, while filtering the array.
var array = [{ t_id: "abc", s_id: "pai" }, { t_id: "pai", s_id: "par" }, { t_id: "pai", s_id: "pas" }, { t_id: "pai", s_id: "pai" }, { t_id: "par", s_id: "pas" }],
keys = ['t_id', 's_id'],
value = 'pai',
result = array.filter(o => keys.some(k => o[k] === value));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 23869
Use filter to return true
either of the conditional matches:
var arr = [{"t_id":"abc","s_id":"pai"},{"t_id":"pai","s_id":"par"},{"t_id":"pai","s_id":"pas"},{"t_id":"pai","s_id":"pai"},{"t_id":"par","s_id":"pas"}];
console.log(arr.filter(item => item.t_id === 'pai' || item.s_id === 'pai'));
Upvotes: 1
Reputation: 1347
You can achieve this by passing around object name and value.
var arr = [
{
"t_id" : "abc",
"s_id" : "pai"
},
{
"t_id" : "pai",
"s_id" : "par"
},
{
"t_id" : "pai",
"s_id" : "pas"
},
{
"t_id" : "pai",
"s_id" : "pai"
},
{
"t_id" : "par",
"s_id" : "pas"
}
]
function myFilter(name, value) {
var filteredArr = arr.filter(obj => obj[name] === value);
return filteredArr;
}
var filterTID = myFilter("t_id", "pai");
var filterSID = myFilter("s_id", "pai");
console.log(filterTID);
console.log(filterSID);
Upvotes: 0