动态多变量过滤函数

Dynamic Multiple Variable Filter Function

总结:
谢谢阅读!我一直在试图弄清楚如何将多个变量(数量未知)传递给一个接受对象数组(数量未知)的参数 简而言之: 我想过滤掉不符合另一个数组中列出的所有条件的人(我也愿意使用 rest 而不是数组)。

代码访问:

这很棒,除了假设我已经知道我要过滤的参数以及我要寻找关联参数的元素。

// 对象数组:

let people = [
    {name: "Steve",  age: 27, country: "America"},
    {name: "Linda",  age: 23, country: "Germany"},
    {name: "Jimena", age: 29, country: "Spain"},
    {name: "Eric",   age: 24, country: "England"},
    {name: "Jacob",  age: 24, country: "America"},
];

let filters = [
    {country: "America"},
    {Age: 24}
];

// 函数:(尝试)

const filterMatch = {}
  
const filterThePeople = ((data, filters) => {
  
    filters.forEach(filter => {
    
        //==========get key and value of filter=====================
        for (const [key, value] of Object.entries(filter)) {
            filterMatch[key] = value
            return {key, value}
        }
      
    })

    data.forEach(person => {
        for (const [key2, value2] of Object.entries(data)) {
            
            return {key2, value2}
        }
    })

      
  })
  console.log(filterThePeople(people, filters))

我不确定是否要将“data.forEach...”语句放在上面的 for 语句中...我正在考虑放置一个 if 或 switch 语句来查找数组每个键,当它找到匹配的键时,它会查看每个键的值,如果键和值都匹配,则 += 到列表...最终到 return 列表到函数。 (至少那是我脑海中想象的解决方案。我完全愿意接受任何和所有实现这一目标的替代方法!)

过滤匹配每个过滤器的人..我可能会补充一点,KEY 的命名在这里非常重要。在您的示例中,您稍后将 Age 作为首都。这也允许您构建这样的过滤器:

let filters = [ {country: "America", age: 24} ];

let people = [ { name: "Steve", age: 27, country: "America", }, { name: "Linda", age: 23, country: "Germany", }, { name: "Jimena", age: 29, country: "Spain", }, { name: "Eric", age: 24, country: "England", }, { name: "Jacob", age: 24, country: "America", }, ];

let filters = [
    {country: "America"},
    {age: 24}
];

let results = people.filter(p => 
  filters.every(f=> Object.keys(f).every(k => p[k] === f[k]))
)

console.log(results);

你可以这样做

let people = [
    {name: "Steve",  age: 27, country: "America"},
    {name: "Linda",  age: 23, country: "Germany"},
    {name: "Jimena", age: 29, country: "Spain"},
    {name: "Eric",   age: 24, country: "England"},
    {name: "Jacob",  age: 24, country: "America"},
];

let filters = [
    {country: "America"},
    {age: 24}
];

const filtered = people.filter(p => filters.every(f => {
 const [key] = Object.keys(f)
 return p[key] === f[key]
}))

console.log(filtered)