簡體   English   中英

Javascript篩選器無法在多個條件下使用

[英]Javascript filter not working with multiple conditions

假設我有這個數組:

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) 

似乎您誤解了forEach的返回值。 在您的示例代碼中, item.category.forEach()完成執行后將始終返回undefined ,這就是為什么它出錯了。

在這種情況下,您應該使用Array.some() ,其返回值是布爾值(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()只是一個附加示例,以防萬一您將來需要它:)!

您這里需要的是some 更換forEachsome

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

您可以對categories使用find方法來過濾最終列表

let filteredArray = array.filter(item => {
    return item.categories.find( category => category.slug === 'another-category');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM