【发布时间】:2017-08-05 10:17:00
【问题描述】:
我正在尝试创建一个产品网格过滤系统。通过在 JSON 对象上调用 .filter(),我得到了我正在寻找的结果。
const filteredProducts = allProducts.filter((a) => {
// return brown or blue products in with omnis tag
const prodTags = a.tags;
return (
prodTags.includes('brown') && prodTags.includes('single-eye') && prodTags.includes('happy') ||
prodTags.includes('brown') && prodTags.includes('single-eye') && prodTags.includes('angry') ||
prodTags.includes('brown') && prodTags.includes('two-eyes') && prodTags.includes('happy') ||
prodTags.includes('brown') && prodTags.includes('two-eyes') && prodTags.includes('angry') ||
prodTags.includes('blue') && prodTags.includes('single-eye') && prodTags.includes('happy') ||
prodTags.includes('blue') && prodTags.includes('single-eye') && prodTags.includes('angry') ||
prodTags.includes('blue') && prodTags.includes('two-eyes') && prodTags.includes('happy') ||
prodTags.includes('blue') && prodTags.includes('two-eyes') && prodTags.includes('angry')
);
});
我很难想出一种方法来使这种动态化。我似乎无法创建一个可以为任意数量的标签自动生成此逻辑的函数。
我有一个看起来像这样的过滤系统(~ 是当前选定的):
-----------
Colors:
-----------
~ brown
gray
~ blue
pink
-----------
Eyes:
-----------
~ single-eye
~ two-eyes
-----------
Emotion:
-----------
~ happy
~ angry
sad
类别之间的逻辑是AND。类别值之间的逻辑是 OR。我有一个创建笛卡尔积数组的函数设置。选定的过滤器数组如下所示:
[
['brown', 'single-eye', 'angry'],
['brown', 'single-eye', 'happy'],
['brown', 'two-eyes', 'angry'],
['brown', 'two-eyes', 'happy'],
['blue', 'single-eye', 'angry'],
['blue', 'single-eye', 'happy'],
['blue', 'two-eyes', 'angry'],
['blue', 'two-eyes', 'happy']
]
这就是我卡住的地方。我似乎无法找到一种方法将这个生成的数组动态集成到 .filter() 中并使用 ||和 && 相应地。
非常感谢任何帮助。
【问题讨论】:
-
不确定预期结果是什么?您可以在 Question 中包含输入数组吗?
标签: javascript arrays ecmascript-6 filtering