[英]filter array within array
我有一系列產品,我想過濾所有這些產品。 這里的級別也是一個數組,因為我使用了復選框,因此如果用戶選擇級別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;
});
});
}
您可以在過濾器中使用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
版本更加干凈,但是您始終可以創建自己的包含函數:
const arrayIncludes = function(array, item) {
return array.indexOf(item) !== -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"}
// ]
這不是簡單匹配那么容易,因為您需要比較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]
}
});
}
// 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"]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.