2017-01-24 184 views
1

我有一個產品陣列,我想過濾所有這些產品的關卡。這裏的級別也是一個數組,因爲我使用了複選框,所以如果用戶選擇級別1,應該顯示具有級別1的產品,並且如果用戶再次選擇級別2,應該顯示具有級別1和2的產品。但是,我正在獲取所有產品而不是選定的級別。陣列內的濾波器陣列

這裏是我的代碼

// sample product data 
products = [ 
{id: "1", sellerLevel: "new", status: "online"}, 
{id: "1", sellerLevel: "1", status: "offline"}, 
{id: "1", sellerLevel: "1", status: "offline"}, 
{id: "1", sellerLevel: "2", status: "online"} 
] 

function productFilterFromLevel({level}) { // level ["new", "1"] 
    return products.filter(function(product) { 
    return level.filter(function(lvl) { 
     return product.sellerLevel === lvl; 
    }); 
    }); 
} 

回答

1

// sample product data 
 
products = [{ 
 
    id: "1", 
 
    sellerLevel: "new", 
 
    status: "online" 
 
}, { 
 
    id: "1", 
 
    sellerLevel: "1", 
 
    status: "offline" 
 
}, { 
 
    id: "1", 
 
    sellerLevel: "1", 
 
    status: "offline" 
 
}, { 
 
    id: "1", 
 
    sellerLevel: "2", 
 
    status: "online" 
 
}] 
 

 
function productFilterFromLevel(level) { 
 
    return products.filter(function(product) { 
 
    return level.indexOf(product.sellerLevel) != -1; 
 
    }); 
 
} 
 

 
console.log(productFilterFromLevel(["new", "1"]));

+0

這對我的情況起作用。謝謝你的幫助。我忘記了indexOf來檢查數組中的元素。 – Serenity

1

你有對象的數組,這是一個偉大的使用情況Array.filter

// sample product data 
products = [ 
{id: "1", sellerLevel: "new", status: "online"}, 
{id: "1", sellerLevel: "1", status: "offline"}, 
{id: "1", sellerLevel: "1", status: "offline"}, 
{id: "1", sellerLevel: "2", status: "online"} 
] 

function filter(products, matches) { 
    return products.filter(product => { 
    return matches.includes(product.sellerLevel); 
    }); 
} 

console.log(filter(products, ['new', '1'])); 

// [ 
// {id: "1", sellerLevel: "new", status: "online"}, 
// {id: "1", sellerLevel: "1", status: "offline"}, 
// {id: "1", sellerLevel: "1", status: "offline"} 
// ] 

https://jsfiddle.net/persianturtle/fL8eupoz/3/

+0

謝謝回答。然而,我在我的問題中提出的問題是我不比較sellerLevel 1或新的,但與水平數組不是一個單一的值。 – Serenity

+0

@ Apprentice,更新 –

2

您可以使用Array.includes您的篩選器

const productFilterFromLevel = ({level}, products) => products 
    .filter(item => level.includes(item.sellerLevel)) 

或不包括您可以在按鍵只是過濾,像這樣

const productFilterFromLevel = function({level}, products) { 
    return products.filter(function(product) { 
    return level.indexOf(product.sellerLevel) !== -1 
    }) 
} 

正如你所看到的includes版本更清潔,但你總是可以使自己的include函數:

const arrayIncludes = function(array, item) { 
    return array.indexOf(item) !== -1 
} 
+0

這讓我想起'includes',+1 –

1

這不是簡單的比賽一樣容易,因爲你需要的sellerLevel的比較:

function productFilterFromLevel(level) { // level ["new", "1"] 
    return products.filter(function(product) { 
    for (var i = 0; i < level.length; i++) { 
     if (level[i] === 'new') { 
     return product.sellerLevel === 'new' 
     } 
     return +product.sellerLevel <= +level[i] 
    } 
    }); 
}