【发布时间】:2021-12-27 01:01:51
【问题描述】:
我目前正在尝试根据所选选项过滤可用产品。
const products = [{
id: 1,
name: 'Safari',
horsepowers: 30,
doors: 4,
gear_type: 'automatic',
wheels: 6
},
{
id: 2,
name: 'Jungle',
horsepowers: 50,
doors: 3,
gear_type: 'automatic',
wheels: 5
},
{
id: 3,
name: 'Moon',
horsepowers: 30,
doors: 4,
gear_type: 'manual',
wheels: 4
}
]
const selectedOptions =
{
horsepowers: 50,
doors: 3,
gear_type: null,
wheels: null
}
通常我会做类似的事情
const availableProducts = products.filter((product) =>
product.horsepowers === selectedOptions.horsepowers &&
product.doors === selectedOptions.doors .... etc
但是,如果用户尚未选择所有可能的选项,我该如何跳过空值、空数组和未定义值?
【问题讨论】:
-
为什么不过滤
selectedOptions以删除具有空值的对?然后获取并迭代其他过滤器测试的键。 -
请添加一些不需要的值的示例。
-
感谢您的众多回答。对大家很有帮助。
标签: javascript arrays filter conditional-statements