基于Javascript中的两个字符串数组进行数据过滤的函数

a function for data filtration based on two arrays of strings in Javascript

我需要阵列过滤方面的帮助。我想根据以下条件过滤对象数组:

注意:这些数组可以为空。当它们为空时,函数应该return原始数组(没有数据过滤)

brands: ["brand 1", "brand 2", "brand 3", "brand 4"],
tags: ["tag1", "tag2", "tag 3", "tag 4"],

我要过滤的对象数组如下所示:

[
 {
    "tags": [
      "tag1"
    ],
    "price": 10.99,
    "name": "Sample name",
    "manufacturer": "brand 1",
  },
 {
    "tags": [
      "tag1", "tag2"
    ],
    "price": 10.99,
    "name": "Sample name",
    "manufacturer": "brand 1",
  },
 {
    "tags": [
      "tag1", "tag3", "tag4"
    ],
    "price": 10.99,
    "name": "Sample name",
    "manufacturer": "brand 4",
  },
 {
    "tags": [
      "tag1", "tag2"
    ],
    "price": 10.99,
    "name": "Sample name",
    "manufacturer": "brand1 ",
  },
]

我的功能看起来像这样只对制造商进行过滤:

const obj = {
  brands: ["brand 1", "brand 2"],
  tags: ["tag1", "tag2", "tag 4"],
}

const filterArray = (obj, array) => {
  let newArray = []
  const byBrands = array.filter((item) =>
    obj.brands.includes(item["manufacturer"].toLowerCase())
  )

  if (byBrands.length > 0) {
    newArray = byBrands
  } else {
    newArray = array
  }

  return newArray;
}

我需要一个功能来同时过滤标签和制造商。

谢谢,Stakoverflow :)

您应该在过滤器对象中使用与要过滤的对象中的属性相匹配的键,否则无法知道 属性 比较的是哪个。除此之外,它只是检查 every() property in the filter object has some() matching entry in the object being filtered. The example ignores empty arrays in the filter object using an OR (||) short-circuit, and uses concat() 是否将每个 属性 评估为数组的问题。

(可以微调使其case-insensitive,搜索子串等)

const input = [{ "tags": ["tag1"], "price": 10.99, "name": "Sample name", "manufacturer": "brand 1", }, { "tags": ["tag1", "tag2"], "price": 10.99, "name": "Sample name", "manufacturer": "brand 1", }, { "tags": ["tag 4"], "price": 10.99, "name": "Sample name", "manufacturer": "brand 2", }, { "tags": ["tag 3"], "price": 10.99, "name": "Sample name", "manufacturer": "brand 1", },]

const obj = {
  manufacturer: ["brand 1", "brand 2"],
  tags: ["tag1", "tag2", "tag 4"],
  name: [], // ignores empty arrays
}

function filterProducts(array, filters) {
  return array.filter(p =>
    Object.entries(filters).every(([k, fs]) =>
      !fs.length || fs.some(f => [].concat(p[k]).some(t => t === f)))
  )
}

console.log(filterProducts(input, obj))