Javascript过滤器无法使用多个条件

时间:2018-04-28 18:19:10

标签: javascript filter

我们假设我有这个数组:

array = [{ 
    name: 'my post',
    categories: [{
        slug: 'a-cat',
        name: 'A Category'
    }
},
{ 
    name: 'my other post',
    categories: [{
        slug: 'another-category',
        name: 'Another Category'
    },
    {
        slug: 'a-cat',
        name: 'A Category'
    }
},
]  

现在,我想过滤它以获取包含类别another-category的所有元素,这是我到目前为止所尝试的内容,但filteredArray中没有任何内容

let filteredArray = array.filter(function (item) {
    return item.categories.forEach(function(cat) {
        return cat.slug === 'another-category'
    })
})

对我做错了什么的想法?



const array = [{
    name: 'my post',
    categories: [{
      slug: 'a-cat',
      name: 'A Category'
    }]
  },
  {
    name: 'my other post',
    categories: [{
        slug: 'another-category',
        name: 'Another Category'
      },
      {
        slug: 'a-cat',
        name: 'A Category'
      }
    ]
  },
]


let filteredArray = array.filter(function(item) {
  return item.categories.forEach(function(cat) {
    return cat.slug === 'another-category'
  })
})

console.log(filteredArray)




3 个答案:

答案 0 :(得分:2)

你似乎误解了forEach的返回值。 在您的示例代码中,item.category.forEach()在完成执行时将始终返回undefined,这就是它出错的原因。

在这种情况下,你应该使用Array.some(),返回值为boolean(true / false)。

let filteredArray = array.filter(function (item) {
    // this mean:
    //  if has ANY <cat>s in array item.categories has slug attribute equal 'another-category': 
    //  return current <item>
    return item.categories.some(function(cat) {
        return cat.slug === 'another-category'
    })
})

**另一个答案是使用.every()

let filteredArray = array.filter(function (item) {
        // this mean:
        //  if NOT(ALL <cat>s in array item.categories haven't .slug attribute  equal  'another-category'): 
        //  return current <item>
        return !item.categories.every(function(cat) {
            return (return cat.slug !== 'another-category')
        });
})

注意:.every()只是一个额外的例子,如果你们将来需要它:)!

答案 1 :(得分:1)

这里需要的是some。将forEach替换为some

return item.categories.some(function(cat) {
    return cat.slug === 'another-category'
})

答案 2 :(得分:1)

您可以使用js方法覆盖find来过滤最终列表

categories