如何根据另一个对象数组过滤一个对象数组?
Posted
技术标签:
【中文标题】如何根据另一个对象数组过滤一个对象数组?【英文标题】:How to filter an array of objects based on another array of objects? 【发布时间】:2019-09-30 08:06:49 【问题描述】:我有两个对象数组,如下所示
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"
]
我想用条件数组过滤数据数组,比如如果条件数组中的条件属性包含专家,那么我需要根据data.Expert = conditions[Expert Conditionindex].value
过滤数据数组然后我需要返回所有符合这个条件的数据。
另一件事是,如果 value: 'ALL'
则无需在该特定条件下进行过滤。
想要的输出是这样的
filteredData = [
"Date": "11/6/2018",
"client": "Verizon",
"Expert": "Ellison, Lauren",
"Coach": "willaim",
"manager": "Brandy Lovings",
"site": "Sundance",
"Metric": "STR"
]
我该如何解决这个问题?
【问题讨论】:
【参考方案1】:您可以使用不带ALL
标志的条件子集进行过滤。
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;
【讨论】:
【参考方案2】:这应该适合你:
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)
【讨论】:
以上是关于如何根据另一个对象数组过滤一个对象数组?的主要内容,如果未能解决你的问题,请参考以下文章