javascript - 在数组中过滤数组

标签 javascript arrays

我有一系列产品,我想用级别过滤所有这些产品。这里的级别也是一个数组,因为我使用了复选框,所以如果用户选择级别 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;
    });
  });
} 

最佳答案

// 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"]));

关于javascript - 在数组中过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41819111/

相关文章:

php - 调用 array() 没有任何用处的参数吗?

python - NumPy 中的 ndarray 和数组有什么区别?

javascript - 具有较低 zIndex 的图层上的 Google map 点击事件

javascript - jQuery 发送并显示每行文本区域的 ajax 结果

javascript - 如何禁用 jQuery Mobile 中的链接按钮?

javascript - 并行运行 Node 和 Apache

javascript - 如何设置类组合的CSS规则?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c# - Linq 的 Skip and Take 是否针对数组进行了优化? [4.0版]

jquery - 传递数组时的数据代码