gpt4 book ai didi

javascript - 根据多个条件过滤对象的JSON数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:37 25 4
gpt4 key购买 nike

我有一个对象的 JSON 数组。我正在创建一个过滤器来过滤这些数据。

var allData = {
"items":[
{
"orderNumber": 1010,
"area": "JAPAN",
"category": "orange",
"orderApprover": "John Smith"
},
{
"orderNumber": 1020,
"area": "EM-JAPAN",
"category": "red",
"orderApprover": "Paul Smith"
},
{
"orderNumber": 1013,
"area": "EMEA",
"category": "orange",
"orderApprover": "Mike Smith"
},
{
"orderNumber": 1140,
"area": "APAC",
"category": "yellow",
"orderApprover": "Jake Smith"
}
]}

如果筛选条件是:(查找 orderNumbers 包含 10 的项目)

然后输出:

{
"items":[
{
"orderNumber": 1010,
"area": "JAPAN",
"category": "orange",
"orderApprover": "John Smith"
},
{
"orderNumber": 1020,
"area": "EM-JAPAN",
"category": "red",
"orderApprover": "Paul Smith"
},
{
"orderNumber": 1013,
"area": "EMEA",
"category": "orange",
"orderApprover": "Mike Smith"
}
]}

如果筛选条件是:(查找 orderNumbers 包含 114 的项目)

然后输出:

{
"items":[
{
"orderNumber": 1140,
"area": "APAC",
"category": "yellow",
"orderApprover": "Jake Smith"
}
]
}

如果过滤条件是:(查找orderNumber包含10且area包含EM的items)

然后输出:

{
"items":[
{
"orderNumber": 1020,
"area": "EM-JAPAN",
"category": "red",
"orderApprover": "Paul Smith"
},
{
"orderNumber": 1013,
"area": "EMEA",
"category": "orange",
"orderApprover": "Mike Smith"
}
]}

有没有办法实现连续过滤器的连接?

编辑:我试图让它变得通用。

我已将过滤器字段值存储在状态对象中。

this.state = {
orderNumberData: '',
areaData: '',
.
.
.
.
}

数组 selectedFilters 存储过滤器。

像这样:

selectedFilters = [orderNumberData, areaData,........]

我现在如何迭代并获得所需的过滤器。我正在尝试遍历 selectedFilters 数组并检查包含所需字符串的每个项目。我不知道如何根据 selectedFilters 数组用 JSON 对象字段填充空白。两者之间需要某种映射。假设如果 selectedFilters[1] = orderNumberData,则 orderNumber 应填入空白。

for(var i=0; i<selectedFilters.length; i++) {
allData.items.filter(item => item.________.toString().includes(this.state[this.state.selectedFilters[i]]))
}

如果我对 JSON 字段进行了硬编码,这会起作用。

allData.items.filter(item => item.orderNumber.toString().includes(this.state[this.state.selectedFilters[i]]))

最佳答案

您可以将约束信息移动到过滤器数组并通过使用 Array#every 检查所有(AND 条件)约束来进行过滤或者如果您只想要一些(或条件),请使用 Array#some .

var data = [{ orderNumber: 1010, area: "JAPAN", category: "orange", orderApprover: "John Smith" }, { orderNumber: 1020, area: "EM-JAPAN", category: "red", orderApprover: "Paul Smith" }, { orderNumber: 1013, area: "EMEA", category: "orange", orderApprover: "Mike Smith" }, { orderNumber: 1140, area: "APAC", category: "yellow", orderApprover: "Jake Smith" }],
filters = [
o => o.orderNumber.toString().includes('10'),
o => o.area.includes('EM')
],
result = data.filter(o => filters.every(fn => fn(o)));

console.log(result);

关于javascript - 根据多个条件过滤对象的JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55751236/

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