gpt4 book ai didi

javascript - 基于 Javascript 过滤器数组的过滤器数组

转载 作者:行者123 更新时间:2023-11-30 11:08:36 26 4
gpt4 key购买 nike

我有一组用户和一组过滤器。

我需要根据过滤器数组过滤用户,但当我这样做时,它会过滤一个数组而不是其他数组

我的过滤器对象如下所示:

filters: {
levels: [],
locations: ['Laois'],
subjects: ['Art']
}

我的用户看起来像这样:

const users = [
{
email: 'example1@gmail.com',
levels: ['Ordinary'],
location: 'Laois',
subjects: ['Art', 'German']
},
{
email: 'example2@gmail.com',
levels: ['Higher', 'Ordinary'],
location: 'Laois',
subjects: ['English', 'German']
}
]

基于上面的过滤器,过滤后用户应该只有一个,因为它包含“Art”和“Laois”:

[{
email: 'example1@gmail.com',
levels: ['Ordinary'],
location: 'Laois',
subjects: ['Art', 'German']
},
]

但我仍然得到了两个用户:

编辑我的代码:

applyFilter = (visable) => {
let { filters, users } = this.state;
const { subjects, locations, levels } = filters;


let filteredUsers = [];
const filteredData = users.filter((user) =>
user.subjects.some(subject => subjects.includes(subject)) ||
locations.some(location => location === user.location) ||
user.levels.some(level => levels.includes(level))
);

console.log(filteredData)


if (!subjects.length && !locations.length && !levels.length) {
filteredUsers = users;
} else {
filteredUsers = filteredData;
}

this.setState({
filterModalVisible: visable,
filteredResults: filteredUsers.length >= 0 ? filteredUsers : [],
});
}

最佳答案

您可以使用 filterevery 方法来执行此操作,方法是检查过滤器值中的每个元素是否都存在于具有相同键的用户值中。

const filters = {"levels":[],"locations":["Laois"],"subjects":["Art"]}
const users = [{"email":"example1@gmail.com","levels":["Ordinary"],"locations":"Laois","subjects":["Art","German"]},{"email":"example2@gmail.com","levels":["Higher","Ordinary"],"locations":"Laois","subjects":["English","German"]}]

const res = users.filter(user => {
return Object.entries(filters)
.every(([key, value]) => {
if (Array.isArray(value)) {
return value.every(filter => {
return user[key] && user[key].includes(filter)
})
} else {
return user[key] == value
}
})
})

console.log(res)

关于javascript - 基于 Javascript 过滤器数组的过滤器数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54689095/

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