JavaScript-根据多个值过滤对象

问题描述:

我需要根据多个值过滤一些数据。 语言标题子弹

I need to filter some data based on multiple values. Language, title and slug

[
{
    de: "4567uy55",
    en: "654321",
    lang: [
      {
        id: "654321",
        language: "English",
        title: "Title1"
      },
      {
        id: "4567uy55",
        language: "German",
        title: "Title2"
      }
    ],
    slug: 'some-slug'
},
...
]

我现在返回的全部具有一个或一部分过滤器的对象(如果标题为这是标题,则单词 this 应该匹配),但我需要返回包含所有对象的对象。
我仅使用对象flattner来获取一个对象中的所有属性和值,但无法使用它过滤所需的方式。

What I have now returns all objects which have one or part of the filters(in case title is This is a title, the word this should match), but I need to return objects which have all of them. I used an object flattner just to get all properties and values in one object, but I can't get it to filter the way I need it.

multiFilter = (arr, filters) => {

console.log(filters)
console.log(arr)

let newArray = []

for (let c of arr) {

    let flatCourse = flatten(c)

    for (let k in flatCourse) {

        const keyArr = k.split('/')
        const filterKeys = Object.keys(filters)

        Object.keys(filters).map((key) => {

            if (keyArr.includes(key)) {

                const flatVal = flatCourse[k].toString().toLowerCase()
                const filterVal = filters[key].toString().toLowerCase()

                console.log(flatVal)
                console.log(filterVal)

                if (flatVal.includes(filterVal)) {
                    arr = []
                    arr.push(c)
                    newArray.push(c)
                }

            }
        })
    }

}

return newArray


}

过滤器如下所示:

[

language:["English"],
title: ["Some title"],
slug:["some slug"]

]


除了混合使用循环和功能链外,您还可以选择其中之一:

Instead of mixing for loops and functional chaining you could just go with one of them:

 multiFilter = (arr, filters) => 
   arr.map(flatten).filter(el => // filter out elements from arr
     Object.entries(filters).every(([fKey, fValues]) => // ensure that every key is included in the object
       Object.entries(el).some(([oKey, oValue]) => 
          oKey.split("/").includes(fKey) && fValues.includes(oValue)// make sure that at least one of the values equals the elements value
       )
     )
  );