Reputation: 63
I have two array of objects like below
conditions= [
{
'condition': 'Expert',
'value': 'All'
},
{
'condition': 'Coach',
'value': 'willaim'
},
{
'condition': 'manager',
'value': 'Brandy Lovings'
},
{
'condition': 'site',
'value': 'ALL'
},
{
'condition': 'client',
'value': 'ALL'
}
]
data=[
{
"Date": "11/6/2018",
"client": "Verizon",
"Expert": "Ellison, Lauren",
"Coach": "willaim",
"manager": "Brandy Lovings",
"site": "Sundance",
"Metric": "STR"
},
{
"Date": "11/6/2018",
"client": "Amzaon",
"Expert": "Ellison, Lauren",
"Coach": "Dash Williamson",
"manager": "David",
"site": "abc",
"Metric": "STR"
}
]
I want to filter data array with the conditions array, like if condition property in conditions array contain Expert then I need to filter data array based on data.Expert = conditions[Expert Conditionindex].value
then I need to return all the data with this conditions.
Another thing is, If value: 'ALL'
then no need of filtering in that particular condition.
The desired output is like
filteredData = [
{
"Date": "11/6/2018",
"client": "Verizon",
"Expert": "Ellison, Lauren",
"Coach": "willaim",
"manager": "Brandy Lovings",
"site": "Sundance",
"Metric": "STR"
}
]
How do I solve this problem?
Upvotes: 0
Views: 65
Reputation: 870
This should work for you:
const conditionsObj={}
conditions.filter(({value})=>value.toLowerCase()!=='all').forEach((condition)=>{
conditionsObj[condition.condition]=condition.value
})
const results=data.filter((item)=>{
let match=false;
Object.keys(conditionsObj).forEach((_key)=>{
if(conditionsObj[_key]===item[_key]){
match=true;
}
})
return match;
})
console.log(results)
Upvotes: 0
Reputation: 386519
You could filter with a subset of conditions without ALL
flag.
var conditions = [{ condition: "Expert", value: "All" }, { condition: "Coach", value: "willaim" }, { condition: "manager", value: "Brandy Lovings" }, { condition: "site", value: "ALL" }, { condition: "client", value: "ALL" }],
data = [{ Date: "11/6/2018", client: "Verizon", Expert: "Ellison, Lauren", Coach: "willaim", manager: "Brandy Lovings", site: "Sundance", Metric: "STR" }, { Date: "11/6/2018", client: "Amzaon", Expert: "Ellison, Lauren", Coach: "Dash Williamson", manager: "David", site: "abc", Metric: "STR" }],
filters = conditions.filter(({ value }) => value.toUpperCase() !== 'ALL'),
result = data.filter(o =>
filters.every(({ condition, value }) => o[condition] === value));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1