条件Java过滤器

dar*_*dub 5 javascript filter ecmascript-6

我有一个包含以下内容的对象:

assets = [
  { id: 1, type: 'image', url: 'image.jpg' },
  { id: 2, type: 'video', url: 'video.mp4' },
]
Run Code Online (Sandbox Code Playgroud)

我想根据用户对IMAGE,VIDEO或ALL的选择进行过滤。

我想不出一种干净的方法来过滤所有情况。

currentOption = 'image'
assets.filter(asset => asset.type === currentOption)
Run Code Online (Sandbox Code Playgroud)

这将适用于IMAGE或VIDEO,但不适用于全部。

我可以签入我的过滤器功能:

const currentOption = 'all'
const filterFunc = asset => {
  if (currentOption == 'all') return true
  return asset.type === currentOption
}
assets.filter(filterFunc)
Run Code Online (Sandbox Code Playgroud)

但是短路过滤器而不迭代每个项目不是更好吗?

编辑: 要回答问题,为什么不一起跳过所有过滤器。我试图使其与框架无关。但这是使用react渲染的。因此,我将不得不执行以下操作:

<div>
{currentOption === 'all' ?
  assets.map(asset => 
   <img src={asset.url} />
  )
  :
  assets.filter(asset => asset.type === currentOption).map(asset =>
   <img src={asset.url} />
  )
}
</div>
Run Code Online (Sandbox Code Playgroud)

另外,这甚至不考虑显示视频的代码。基本上,我试图减少视图代码中的重复项。

小智 6

我或多或少会同意你的建议:

assets.filter(asset => currentOption === "all" || asset.type === currentOption);
Run Code Online (Sandbox Code Playgroud)

请记住,filter() 无论如何都会迭代所有项目。


tri*_*cot 5

您可以使用三元运算符来决定是否应用过滤器:

currentOption === 'all' ? assets : assets.filter(asset => asset.type === currentOption)
Run Code Online (Sandbox Code Playgroud)

您在问题末尾添加的图像映射可以这样写:

(currentOption === 'all' ? assets : assets.filter(asset => asset.type === currentOption))
    .map( asset => <img src={asset.url} /> )
Run Code Online (Sandbox Code Playgroud)