JavaScript Filter Func:在多个条件下进行过滤(可能为true) [英] JavaScript Filter Func: filter on multiple conditions (either could be true)

查看:63
本文介绍了JavaScript Filter Func:在多个条件下进行过滤(可能为true)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是我所忽略的超级简单的东西.

Might be something super simple that I am over looking.

我有一个包含一些信息的对象数组.根据用户的操作,我想过滤掉一些对象;

I have an array of objects that contains some info. Based on user action, I'd like to filter out some objects;

let arr = [
 {'num': 1, 'name': 'joe'},
 {'num': 2, 'name': 'jane'},
 {'num': 3, 'name': 'john'},
 {'num': 3, 'name': 'johnny'},
]

我尝试了什么

 function filterArr(arr) {
  return arr.filter(obj => {
    if(obj.num && obj.num !== 1) {
      return obj;
    }
    if(obj.num && obj.num !== 3) {
     return obj;
    }
  })
}

当我运行filterArr时,我将返回到原始数组,但预期结果应仅为 {'num':2,2,'name':'jane'},.我可以在两个嵌套条件中都使用console.log.

when i run filterArr, I am returned back the original array, but the expected result should be just {'num': 2, 'name': 'jane'},,. I can console.log inside both of the nested condition.

任何基于2个条件中的1个为真的过滤数组的帮助将不胜感激.

Any help of filtering array based on 1 of 2 conditions being true would be appreciated.

推荐答案

如果 if 条件,则每个 num 都会通过其中一个不是宇宙中同时等于1和3的数字**.您可以将&& 条件链接到 filter 中以检查所有条件:

Every single num will pass either of your if conditions because there isn't a number in the universe which is equal to 1 and 3 at the same time**. You can just chain the && condition inside the filter to check for all of them:

let arr = [
 {'num': 1, 'name': 'joe'},
 {'num': 2, 'name': 'jane'},
 {'num': 3, 'name': 'john'},
 {'num': 3, 'name': 'johnny'},
]

let filtered = arr.filter(a => a.num && a.num !== 3 && a.num !== 1)

console.log(filtered)

(**除非它是 0 null undefined 或任何

(**Unless it's 0, null, undefined or any of the falsy values of course. In which case they will fail the obj.num condition of both ifs)

这篇关于JavaScript Filter Func:在多个条件下进行过滤(可能为true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆