最近在工作上遇到需要多條件篩選,且條件為空就不進行判斷,花了一點時間才研究出怎麼做
以下是解法
const originItems =
[{id:1, live:true, name:"test1",color:"red",size:"large"},
{id:2, live:true,name:"test2",color:"blue",size:"large"},
{id:3, live:true,name:"test3",color:"green",size:"medium"},
{id:4, live:false, name:"test4",color:"red",size: "small"},
{id:5, live:false, name:"test5",color:"blue",size: "small"},
{id:6, live:false, name:"test6",color:"green",size:"medium"}];
const sort = {live: true, color: "", size:"large"}
const result = originItems.filter( (o) =>
(!sort.live || o.live === sort.live) && (!sort.color || o.color === sort.color)
&& (!sort.size || o.size === sort.size)
)
console.log(result)
結果如下:
0 Comments:
張貼留言