使用include()

时间:2019-04-29 14:23:22

标签: javascript

因此,我正在使用将标签用作搜索过滤器的应用程序中工作。但是,使用两个标签时无法得到结果。例如,名为CoffeShop的商店有两个标签“ Coffee”和“ Cookies”。传递其中一个时,它将返回CoffeShop,但传递两个标签时,则不返回任何内容。

我尝试使用loadash和其他一些东西,但到目前为止都没有起作用。

let array = [
  {
    "name": "CoffeShop",
    "tag":[
      "Coffee",
      "Cookies",
    ],
  },
   {
    "name": "TeaShop",
    "tag":[
      "Tea",
    ],
  },
   {
    "name": "IceCreamShop",
    "tag": [
      "Ice Cream",
    ]
  },
]



let tags = ['Coffee', 'Cookies']   
result = array.filter(item => item.tag.some(t =>  t.includes(tags)))
console.log(result)

实际结果只能给我一家CoffeShop的商店,但我什么也没得到

5 个答案:

答案 0 :(得分:3)

仅反向包含应该是数组。include(项目

let array = [
  {
    "name": "CoffeShop",
    "tag":[
      "Coffee",
      "Cookies",
    ],
  },
   {
    "name": "TeaShop",
    "tag":[
      "Tea",
    ],
  },
   {
    "name": "IceCreamShop",
    "tag": [
      "Ice Cream",
    ]
  },
]



let tags = ['Coffee', 'Cookies']  

result = array.filter(item => item.tag.some(t =>  tags.includes(t)))

console.log(result)

答案 1 :(得分:3)

let array = [
  {
    "name": "CoffeShop",
    "tag":[
      "Coffee",
      "Cookies",
    ],
  },
   {
    "name": "TeaShop",
    "tag":[
      "Tea",
    ],
  },
   {
    "name": "IceCreamShop",
    "tag": [
      "Ice Cream",
    ]
  },
]
const _strip = str => str.replace(/\s/g, '')
const _minimize = arr => arr.map(t => _strip(t.toLowerCase()))

const getShopWithTags = (shops = [], tags = []) => {
  tags = _minimize(tags)
  return array.filter(({tag}) => tags.includes(..._minimize(tag)))
}

let tags = ['Coffee', 'Cookies']  
let result = getShopWithTags(array, tags)
console.log(result)

tags = ['Coffee', 'Cookies', 'Ice Cream']
result = getShopWithTags(array, tags)
console.log(result)

let array = [
  {
    "name": "CoffeShop",
    "tag":[
      "Coffee",
      "Cookies",
    ],
  },
   {
    "name": "TeaShop",
    "tag":[
      "Tea",
    ],
  },
   {
    "name": "IceCreamShop",
    "tag": [
      "Ice Cream",
    ]
  },
]

let tags = ['Coffee', 'Cookies']  
let result = array.filter(({tag}) => tags.includes(...tag))
console.log(result)

tags = ['Coffee', 'Cookies', 'Ice Cream']
result = array.filter(({tag}) => tags.includes(...tag))
console.log(result)

答案 2 :(得分:2)

您需要像tags.includes(t)那样做。在您的代码中,您刚刚反转了包含,它应该是Array.include(item)

let array = [
  {
    "name": "CoffeShop",
    "tag":[
      "Coffee",
      "Cookies",
    ],
  },
   {
    "name": "TeaShop",
    "tag":[
      "Tea",
    ],
  },
   {
    "name": "IceCreamShop",
    "tag": [
      "Ice Cream",
    ]
  },
]



let tags = ['Coffee', 'Cookies']   
result = array.filter(item => item.tag.some(t =>  tags.includes(t)))
console.log(result)

答案 3 :(得分:2)

问题是Array.prototype.includes()会在标签内寻找一个数组,而不会自动为您检查数组中的所有值。您可以执行以下操作:

result = array.filter(item => tags.every(tag => item.tag.includes(tag)));

答案 4 :(得分:0)

假设您要查找包含 all 标签的条目,则必须检查cron.yaml是否包含array[n].tags中的所有项目:

tags