gpt4 book ai didi

javascript - 如何根据另一个对象数组过滤一个对象数组?

转载 作者:行者123 更新时间:2023-12-01 01:00:40 24 4
gpt4 key购买 nike

我有两个如下所示的对象数组

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"
}
]

我想用条件数组过滤数据数组,比如如果条件数组中的条件属性包含 Expert 那么我需要根据 data.Expert = Conditions[Expert Conditionindex].value 过滤数据数组那么我需要返回符合此条件的所有数据。

另一件事是,如果值:'ALL'则无需在该特定条件下进行过滤。

所需的输出如下

filteredData = [
{
"Date": "11/6/2018",
"client": "Verizon",
"Expert": "Ellison, Lauren",
"Coach": "willaim",
"manager": "Brandy Lovings",
"site": "Sundance",
"Metric": "STR"
}
]

如何解决这个问题?

最佳答案

您可以使用不带 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; }

关于javascript - 如何根据另一个对象数组过滤一个对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56111059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com