我需要实现过滤对象数组的函数。 Filters数组由具有属性名称的对象和要在用户中为给定属性进行过滤的值组成。
示例:
var filters = [
{
column: 'username',
value: 'test user'
},
{
column: 'name',
value: 'test name'
}
]
var users = [
{
name: 'test name user',
username: 'some test user'
},
{
name: 'another name',
username: 'another username'
}
]
// filter logic
console.log(users); // [{'name': 'test name user', 'username': 'some test user'}]
答案 0 :(得分:4)
您可以通过迭代Array#filter(或者 - 如果至少有一个匹配)或Array#some(并且 - 所有必须匹配)来迭代用户列表和Array#every。
var filters = [{"column":"username","value":"test user"},{"column":"name","value":"test name"}];
var users = [{"name":"test name user","username":"test user"},{"name":"another name","username":"another username"}];
var result = users.filter(function(user) {
return filters.some(function(filter) { // use some for Or, and every for And
return user[filter.column] === filter.value;
});
});
console.log(result);
答案 1 :(得分:1)
你也可以使用Functions#ArrowFunctions和сhange原始数组,如:
var filters = [{"column":"username","value":"test user"},{"column":"name","value":"test name"}];
var users = [{"name":"test name user","username":"test user"},{"name":"another name","username":"another username"}];
users = users.filter((user) => {
return filters.some((filter) => {
return user[filter.column] === filter.value;
});
});
console.log(users);