我有一系列产品,我想过滤所有这些产品。这里的级别也是一个数组,因为我使用了复选框,所以如果用户选择级别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;
});
});
}
答案 0 :(得分: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
版本更清晰,但您始终可以创建自己的包含功能:
const arrayIncludes = function(array, item) {
return array.indexOf(item) !== -1
}
答案 1 :(得分: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"}
// ]
答案 2 :(得分: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]
}
});
}
答案 3 :(得分: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"]));